Can I use __init__.py to define global variables?

后端 未结 4 2019
一生所求
一生所求 2020-11-29 17:24

I want to define a constant that should be available in all of the submodules of a package. I\'ve thought that the best place would be in in the __init__.py fil

4条回答
  •  旧巷少年郎
    2020-11-29 18:14

    You should be able to put them in __init__.py. This is done all the time.

    mypackage/__init__.py:

    MY_CONSTANT = 42
    

    mypackage/mymodule.py:

    from mypackage import MY_CONSTANT
    print "my constant is", MY_CONSTANT
    

    Then, import mymodule:

    >>> from mypackage import mymodule
    my constant is 42
    

    Still, if you do have constants, it would be reasonable (best practices, probably) to put them in a separate module (constants.py, config.py, ...) and then if you want them in the package namespace, import them.

    mypackage/__init__.py:

    from mypackage.constants import *
    

    Still, this doesn't automatically include the constants in the namespaces of the package modules. Each of the modules in the package will still have to import constants explicitly either from mypackage or from mypackage.constants.

提交回复
热议问题