Trying to import module with the same name as a built-in module causes an import error
You will want to read about Absolute and Relative Imports which addresses this very problem. Use:
from __future__ import absolute_import
Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (from .email import ...
) to access your own package.
NOTE: The above from ...
line needs to be put into any 2.x Python .py
files above the import ...
lines you're using. In Python 3.x this is the default behavior and so is no longer needed.
Python error ImportError: No module named
Based on your comments to orip's post, I guess this is what happened:
- You edited
__init__.py
on windows. - The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
- You used WinSCP to copy the file to your unix box.
- WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data."
- The missing
__init__.py
(now called__init__.py.bin
) means python doesn't understand toolkit as a package. - You create
__init__.py
in the appropriate directory and everything works... ?
Can I import a local module with the same name as a standard-library one?
Rename your internal file to something like my_queue.py
and import it into your file like this. That avoids bad practices like from queue import *
and name conflicts with the standard library which is most likely the problem you are running into now.
import my_queue
def driver():
q = my_queue.Queue()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
print("The prority of the job is: " + new_item.job_priority)
print("The job type is: " + new_item.job_type)
Unable to import a module that is definitely installed
In my case, it is permission problem. The package was somehow installed with root rw permission only, other user just cannot rw to it!
Importing from builtin library when module with same name exists
The accepted solution contains a now-deprecated approach.
The importlib documentation here gives a good example of the more appropriate way to load a module directly from a file path for python >= 3.5:
import importlib.util
import sys
# For illustrative purposes.
import tokenize
file_path = tokenize.__file__ # returns "/path/to/tokenize.py"
module_name = tokenize.__name__ # returns "tokenize"
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
So, you can load any .py file from a path and set the module name to be whatever you want. So just adjust the module_name
to be whatever custom name you'd like the module to have upon importing.
To load a package instead of a single file, file_path
should be the path to the package's root __init__.py
ModuleNotFoundError' when trying to import module from imported package
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using
“dotted module names”. For example, the module nameA.B
designates a
submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the
directories as containing packages; this is done to prevent
directories with a common name, such asstring
, from unintentionally
hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
Most likely due to circular import in Python
It seems like the program file you have created is named threading.py
, and you are importing a module also called threading
. This causes a circular import because your file is shadowing the built-in module.
Please rename your program (e.g., threading_example.py
).
import error: 'No module named' *does* exist
My usual trick is to simply print sys.path
in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve
. Then check dirs & files in the places that path shows..
You do that by first having:
import sys
in python 3 with the print function:
print(sys.path)
or in python 2 with print expression:
print sys.path
Related Topics
Unsupported Operand Type(S) for +: 'Int' and 'Str'
What Is the Most Pythonic Way to Pop a Random Element from a List
When Would the -E, --Editable Option Be Useful with Pip Install
Sorting Text File by Using Python
Why Does Str(Float) Return More Digits in Python 3 Than Python 2
How to Set Timeout on Python's Socket Recv Method
How to Retrieve Inserted Id After Inserting Row in SQLite Using Python
Capture Keyboardinterrupt in Python Without Try-Except
Add Pygame Module in Pycharm Ide
Python JSON Parser Allow Duplicate Keys
What Do the Python File Extensions, .Pyc .Pyd .Pyo Stand For
Add X and Y Labels to a Pandas Plot
Python Assigning Multiple Variables to Same Value? List Behavior