Can I use __init__.py to define global variables?

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

    You can define global variables from anywhere, but it is a really bad idea. import the __builtin__ module and modify or add attributes to this modules, and suddenly you have new builtin constants or functions. In fact, when my application installs gettext, I get the _() function in all my modules, without importing anything. So this is possible, but of course only for Application-type projects, not for reusable packages or modules.

    And I guess no one would recommend this practice anyway. What's wrong with a namespace? Said application has the version module, so that I have "global" variables available like version.VERSION, version.PACKAGE_NAME etc.

提交回复
热议问题