Can I use __init__.py to define global variables?

后端 未结 4 2025
一生所求
一生所求 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:13

    You cannot do that. You will have to explicitely import your constants into each individual module's namespace. The best way to achieve this is to define your constants in a "config" module and import it everywhere you require it:

    # mypackage/config.py
    MY_CONST = 17
    
    # mypackage/main.py
    from mypackage.config import *
    

提交回复
热议问题