0

I have a python module e.g. myModule in a subfolder and I have two files:

__init__.py:

from _auxiliary import *

_auxiliary.py:

myvar=False

def initialize():
    global myvar
    myvar=5

Now in ipython when I run:

>> import myModule
>> myModule.initialize()

the variable myModule.myvar is unchanged i.e. False

This does not happen if I put everything in __init__.py

Any idea on how to fix it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
dadopap
  • 1
  • 2
  • why do you want to use a global variable such as `myvar` in the first place? – Peter Varo Mar 15 '14 at 21:42
  • I am writing a module that manages connections to a server, and the global variable stores the object that manages the connections – dadopap Mar 15 '14 at 22:30

2 Answers2

1

The short answer is that globals in Python are global to a module, not across all modules. (This is a bit different from other languages and can cause some confusion).

An easy way to solve this (there are some others) is to define a getter method in the original module, in your case:

_myvar=False

def initialize():
    global _myvar
    _myvar=5

def myvar():
    global _myvar
    return _myvar

So you can access the _myvarinstance with the correct value from whatever module.

import myModule
myModule.initialize()
print("myvar value:", myModule.myvar())

Previous code will show "myvar value: 5"

Roberto
  • 8,586
  • 3
  • 42
  • 53
0

Python - Visibility of global variables in imported modules

The problem is that globality is relatve to the module in question.

You could import _auxiliary directly:

from mymodule import _auxiliary
_auxiliary.initialize()
print _auxiliary.myvar
Community
  • 1
  • 1
Yano
  • 598
  • 5
  • 12