开发者

how to have global variables among different modules in Python

开发者 https://www.devze.com 2022-12-20 21:07 出处:网络
I investigated that scope of glob开发者_开发百科al variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __bui

I investigated that scope of glob开发者_开发百科al variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck.

thanks in advance!


You can access global variables from other modules by importing them explicitly.

In module foo:

  joe = 5

In module bar:

  from foo import joe
  print joe

Note that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.


Python does not support globals shared between several modules: this is a feature. Code that implicitly modifies variables used far away is confusing and unmaintainable. The real solution is to encapsulate all state within a class and pass its instance to anything that has to modify it. This can make code clearer, more maintainable, more testable, more modular, and more expendable.


Scopes beyond the local must be written to via a reference to the scope, or after a global or nonlocal (3.x+) directive.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号