2

I investigated that scope of global 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!

S.Lott
  • 384,516
  • 81
  • 508
  • 779
pars
  • 3,700
  • 7
  • 38
  • 57

3 Answers3

5

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.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 2
    It's even better not to store mutable state in global variables at all, but rather to use classes. – Mike Graham Feb 19 '10 at 17:31
  • @Eli Bendersky, what do you mean by "It's much better to hide access to a module's variables by using functions"? @ Mike Graham, what do you mean by "use classes"? How do you do that to get what he wants? – LWZ Feb 16 '13 at 04:13
  • 1
    @LWZ: What I meant is that when a module lets other modules directly access its data, it may lead to hard-to-debug problems. If access to global data is absolutely required for some reason, at least get/set functions should be provided. These functions make it much easier to modify the code later (say, replace the global data by something else) and debug it if problems arise. – Eli Bendersky Feb 16 '13 at 13:27
3

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.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
0

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358