0

I'm trying to use a global variable, and somehow I'm ending up with two versions of that variable. Can anyone see how this could happen?

My simplified scenario looks like this

a/
 init.py
 b/
   init.py
   file1.py
   file2.py

My first init.py has

from b.file1 import *
from b.file2 import *

In file1.py I have __all__=[stuff, global_variable] and following

global_variable = None
def doit():
  global global_variable
  global_variable = 1
  print("set global variable to %s" %(global_variable))

So finally when I do this:

import a
a.doit()
print(a.global_variable)

I see

set global variable to 1
None 
Yaroslav Bulatov
  • 57,332
  • 22
  • 139
  • 197
  • 3
    `import *` makes a scope-local version (i.e. copy) of your module-global.. – thebjorn May 24 '16 at 04:07
  • 1
    All "global" variables in Python are global to the module they're in. `import *` creates a *new* global variable in the importing module, which is not linked in any way to the variable in the module it was imported from. – BrenBarn May 24 '16 at 04:11
  • OK, that solves mystery, anyone knows where in Python docs this is documented? – Yaroslav Bulatov May 24 '16 at 04:22

1 Answers1

3

From the official tutorial:

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practise in production code.

Remember, there is nothing wrong with using from Package import specific_submodule! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.

Emphasis added.

The from module import * syntax is not recommended (also see this question). Try aliasing each module into its own concise namespace:

import b.file1 as f1
import b.file2 as f2
Community
  • 1
  • 1
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97