Is it possible to access the variables in __init__.py from the modules in the same package?

前端 未结 4 616
情话喂你
情话喂你 2021-02-07 01:41

I have a hello1 package that contains good.py module.

hello1
├── __init__.py
└── good.py

The init module has a variable

相关标签:
4条回答
  • 2021-02-07 02:02

    If you don't like sys.path.append(...) you could run your script as

    python -m hello1.good
    

    in the directory containing the "hello1"-directory or use the PYTHONPATH environment variable instead of sys.path.

    0 讨论(0)
  • 2021-02-07 02:05

    You have to explicit import the constants you want to use.

    It's preferable to have all your constants in a "config" file (i.e. config.py) ) and then if you want them in the package namespace, import them.

    init.py file:

    from package.config import *
    

    it's more clear that way

    0 讨论(0)
  • 2021-02-07 02:07

    If I'm not mistaken you want to do something like:

    python hello1/good.py
    

    Since good.py is a submodule of a package you shouldn,'t run it directly; keep in mind that when directly executing it, then it isn't considered as part of the hello1 package, which prevents relative imports and the current directory is the one that contains the file, hence hello1 cannot be found if it isn't part of the PYTHONPATH. Instead you can run it using the -m switch of the python interpreter:

    -m mod : run library module as a script (terminates option list)

    I personally don't like using the interpreter options to execute a python file. I'd rather have an independent launcher file good.py that imports the hello1.good module and uses it to do what it has to do.

    0 讨论(0)
  • 2021-02-07 02:15

    From Python: import the containing package:

    Importing __init__ seems to work fine.

    import __init__
    
    class Good(object):
        def __init__(self):
            print hello1.A
    
    0 讨论(0)
提交回复
热议问题