1

I have several globals variables in the begining of the Python script and several Classes which use these variables in some methods. I want to keep classes in separate files and load them in main script, but this doesn't work as I expect (and as it works in PHP).

Example of problem:

main.py (the one I run for execution)

global_var = 'my global var value'
from myimport import *
print_global()

Output:

I am loaded!
Traceback (most recent call last):
File "import.py", line 3, in <module>
    print_global()
File "myimport.py", line 3, in print_global
    print(global_var)
NameError: global name 'global_var' is not defined

myimport.py

print('I am loaded!')
def print_global():
    print(global_var)

If I write instruction to import all code (*) into the current namespace, why does function starts in separate module namespace, where global_var is underfined, but not in the name space where it is imported to?

What is the nice Pythonic way to do code separation as I described?

DaneSoul
  • 4,491
  • 3
  • 21
  • 37
  • 1
    Write the code in a way that you don't need to do this. In Python, you either define it in the module or import it from another. – Simeon Visser Apr 10 '15 at 22:02
  • There is type of config with globals which are used than in different methods. It's not good idea to pass them as arguments, but I am thinking about place all these globals in separate module and import them inside my modules with classes – DaneSoul Apr 10 '15 at 22:11
  • 1
    This may help: http://stackoverflow.com/questions/1383239/can-i-use-init-py-to-define-global-variables – Gerrat Apr 10 '15 at 22:11

1 Answers1

1

I would recommend a different approach but this would work:

global_var = 'my global var value'
from myImport import *
__builtins__.global_var = global_var

Global variables are only accessible in the module they are created in. You could make your function takes arguments and pass them in after importing.

Python looks in local, enclosing , global and finally builtins so by adding __builtins__.global_var = global_var the variable is available to every module.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • So __builtins__ is sort of "superglobals" which can be seen in any imported module? – DaneSoul Apr 10 '15 at 22:14
  • @DaneSoul, if you `print(__builtin__.__dict__)` you will see range, zip, len etc.. so by adding to that it makes the variable globally available just like zip or range or any other builtin – Padraic Cunningham Apr 10 '15 at 22:20
  • Ah, I see. But isn't it bad practice to add them there? – DaneSoul Apr 10 '15 at 22:25
  • @DaneSoul, like I said in my answer I would recommend a different approach but in c for instance variables are global unless you use the static keyword so it is not unheard of. Without knowing exactly the use case it is hard to know exactly what to recommend. – Padraic Cunningham Apr 10 '15 at 22:39