Different Ways of Importing Modules in Python
2012-10-22
There are several ways for you to import modules into python, but they will determine how you can reference the attributes inside the modules. Take the math module for example:
- import math
In this case, you are telling the interpreter that you are going to use the module, however the functions and constants in the module are not imported to the current namespace, which means you need to use math.pi, math.sin(), math.cos().... to reference all the functions in this module - from math import pi, sqrt
It imports math.pi, math.sqrt into current namespace, so you can use pi, and sqrt. But other module attributes (like sin, and cos) are not accessible. - from math import *
Then use pi, sqrt, cos, sin, and anything else defined by the module. However on one hand, there may exist conflicts between different modules containing functions with same names; on the other hand, it makes your code less readable. Another reason is that when you are debugging, all the global constants inside these modules will show up in your stackData, which makes it more difficult for you to find the variables you created. - import math as m
Then use m.pi. It's for both simplicity and clarity!
The choice is up to you!
Note, if you choose this way:
import yourmodule
After you made changes to the code on the fly, reload is like:
reload(yourmodule)
If you only imported part of the module, say a function. What I did is to pop up the module from the system path, and then reload it. Anyone who knows a better solution, please leave a message to me
import sys
sys.modules.pop('yourmodule')
from yourmodule import yourfunction