I am researching module usage in python just now and thought I would answer the question Markus asks in the comments above (“How to import variables when they are embedded in modules?”) from two perspectives:
- variable/function, and
- class property/method.
Here is how I would rewrite the main program f1.py to demonstrate variable reuse for Markus:
import f2 myStorage = f2.useMyVars(0) # initialze class and properties for i in range(0,10): print "Hello, " f2.print_world() myStorage.setMyVar(i) f2.inc_gMyVar() print "Display class property myVar:", myStorage.getMyVar() print "Display global variable gMyVar:", f2.get_gMyVar()
Here is how I would rewrite the reusable module f2.py:
# Module: f2.py # Example 1: functions to store and retrieve global variables gMyVar = 0 def print_world(): print "World!" def get_gMyVar(): return gMyVar # no need for global statement def inc_gMyVar(): global gMyVar gMyVar += 1 # Example 2: class methods to store and retrieve properties class useMyVars(object): def __init__(self, myVar): self.myVar = myVar def getMyVar(self): return self.myVar def setMyVar(self, myVar): self.myVar = myVar def print_helloWorld(self): print "Hello, World!"
When f1.py is executed here is what the output would look like:
%run "f1.py" Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Display class property myVar: 9 Display global variable gMyVar: 10
I think the point to Markus would be:
- To reuse a module’s code more than once, put your module’s code into functions or classes,
- To reuse variables stored as properties in modules, initialize properties within a class and add “getter” and “setter” methods so variables do not have to be copied into the main program,
- To reuse variables stored in modules, initialize the variables and use getter and setter functions. The setter functions would declare the variables as global.