Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Local module over global python

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"
like image 556
jbills Avatar asked Jul 15 '12 04:07

jbills


People also ask

Can you manually import a module in Python?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

Why do I need __ init __ py?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

What are the three ways to import modules in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.


1 Answers

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.

like image 184
Greg Hewgill Avatar answered Sep 28 '22 19:09

Greg Hewgill