Import local module on top of global python

I have 2 python files. One is trying to import the second. My problem is that the second is called math.py. I can not rename it. When I try to call a function inside math.py, I cannot, because the result is a global math module. How do I import a local file instead of a global one. I am using Python 2.7 and this is (approximately) my import status:

cstr = "math" command = __import__(cstr) 

Later I will try:

 command.in_math_py_not_global() 

Edit: a more complete example:

 def parse(self,string): clist = string.split(" ") cstr= clist[0] args = clist[1:len(clist)] rvals = [] try: command = __import__(cstr) try: rvals.extend(command.main(args)) except: print sys.exc_info() except ImportError: print "Command not valid" 
+4
source share
2 answers

Python processes have one namespace for loaded modules. If for some reason you (or any other module) have already loaded the standard math module, then trying to load it again using import or __import__() will simply return a link to the already loaded module. You should check this with print id(math) and compare with print id(command) .

Although you stated that you cannot change the name of math.py , I suggest you do it. You get the name of the module to download from the user. You can change this before using the __import__() function to add a prefix. For instance:

 command = __import__("cmd_" + cstr) 

Then rename math.py to cmd_math.py and you will avoid this conflict.

+3
source

You can use relative imports:

 from . import math 

http://docs.python.org/tutorial/modules.html#intra-package-references

+2
source

All Articles