6

I have a 2 python files. One is trying to import the second. My problem is that the second is named math.py. I can not rename it. When I attempt to call a function that is located inside math.py, I can not because I end up with the global math module. How would I import my local file instead of the global. I am using Python 2.7, and this is(roughly) my import statment:

cstr = "math"
command = __import__(cstr)

Later I 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
  • 1
    I just tried creating a test.py with import math, and a math.py in the same directory, and it worked fine. I could call math.foo() in my own math.py with no problem. Commented Jul 15, 2012 at 4:10
  • I get AttributeError("'module' object has no attribute 'main'",) Commented Jul 15, 2012 at 4:22
  • Can you provide a small, complete example that shows exactly what you are doing to cause that error? Commented Jul 15, 2012 at 4:24
  • There, I am basicly letting the user input a string, with the first word of that string used as a command. The command is passed on to a module named after the command. In this case I have math with a file called math.py. Commented Jul 15, 2012 at 4:28

2 Answers 2

3

Python processes have a single namespace of loaded modules. If you (or any other module) has already loaded the standard math module for any reason, then trying to load it again with import or __import__() will simply return a reference to the already-loaded module. You should be able to verify this using print id(math) and comparing with print id(command).

Although you've stated that you are unable to change the name of math.py, I suggest you can. You are getting the name of the module to load from the user. You can modify this before actually using the __import__() function to add a prefix. For example:

command = __import__("cmd_" + cstr)

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'll try your second suggestion. The first did not work, I got a name error saying math is not defined.
3

You could use relative imports:

from . import math

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

1 Comment

Thats not good enough for what I need. In any case I have tried that and only gotten package errors.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.