Reputation: 9708
For the sake of argument, let us say that I wanted to create my own module with a name like math (which is already pre-defined) and then import it from another module. Here is the directory structure of my code:
__init__.py
math.py
So in the __init__.py
I wish to do like
from math import whatever
If I run __init__.py
, the built-in math will be chosen instead of the math module I have included, but I want to access my math module. The only way I have found to get around this is to simply rename math.py to something different like mymath.py. How can I accomplish this while keeping the original name of the module?
Upvotes: 3
Views: 201
Reputation: 85603
if your package is called testpack you can do:
testpack/myfile.py
import math
from testpack import math as mymath
print (math.sin(3))
print (mymath.hello())
where testpack/math.py is:
def hello():
print ('this is math')
this gives you:
0.14112000806
this is math
so you can use both math modules
Edit: Updated for python 3.x
Note: The folder estructure is:
mypackages\
__ini__.py
..........
..........
testpack\
__init__.py
math.py
myfile.py
Upvotes: 1
Reputation: 56881
First of all, it is a bad idea to name your module with the same name as stdlib modules. You may not know when you will trip over unexpected results.
Secondly, what you are saying is perfectly possible.
foo
.__init__.py
with the content you mentioned.math.py
with a content such as print "something"
python __init__.py
you will that something is printed.Perhaps you are doing something else?
Upvotes: 3
Reputation: 82028
Generally it is frowned upon to replace default modules -- you don't know the side effects. I think I should first recommend that you place it in some subfolder (if it is in the folder "my" you could just import my.math as math
), after that I suggest renaming it.
If you must, you can then make sure the path to math.py is first in sys.path. You could probably just do:
import sys, os
sys.path.insert(0,os.getcwd())
Upvotes: 2