Importing Modules: Mymodule - Py Is The Module To Be Imported and Contains This
Importing Modules: Mymodule - Py Is The Module To Be Imported and Contains This
Importing modules
The concept of importing modules may lead to some confusion, especially if you expect a
behaviour similar to other programming languages.
To see clearer I did some simple tests.
mymodule.py is the module to be imported and contains this:
print "HAHA"
def sayhi():
print "Hi"
class Hello:
def __init__(self):
print "HELLO"
The main program for the test that imports mymodule is located in the same directory.
I tried different importing mechanisms:
HAHA
HELLO
Hi
So:
1. All code residing in the imported module is executed, even if only selected functions or
objects are imported explicitely.
2. The 3 different methods of importing give the same result, as expected.
3. If the imported module is found in the same folder as the main program, there is no problem.
_______________________________________________________________________________
x = 1
print „hello“
The first sets a variable, the second tells us that the module has well been imported.
import mymodule
print x
Second try:
print x
Now we have explicitely imported the name x from the namespace of mymodule.
So it is known to the main program. And so this works correctly!
Third try:
This works also as we import the whole namespace to the main program.
Conclusion:
If we want to use variables defined in an imported module, we must import the whole
namespace (from mymodule import *) or seletively import the needed variables (from
mymodule import x).
First try:
y=1
import mymodule
and mymodule:
print 'hello'
print y
This does not work, as main program and mymodule have different namespaces.
Even a statement global y in one or both files does not help.
The solution:
Use get and set functions and a globaql variable in the imported module:
mymodule:
global y
y=-1 # default value
def set_y(yvalue):
global y
y=yvalue
4
def get_y():
return y
def print_y():
print y
Note:
In mymodule, it is important to use the global statement in the set_y function, because here the
value is changed. When the value is only read, as in print_y or get_y, the global statement is not
needed.
Conclusion:
• At module level (for a module that shall be imported), it is good to put the whole code
into functions that can be called from the outside.
• Variables declared with 'global' are global at module level, but not outside of it!
A still more pythonic way would be to use only objects in the imported module.