What are the reserved Python module/package names? - python

I got a strange error while working with Python unittest. I have two folders in my project:
project
code
__init__.py (empty)
app.py (defines my App class)
test
test.py (contains my unit tests)
test.py is:
import os, sys, unittest
sys.path.insert(1, os.path.join(sys.path[0],'..'))
from code.app import App
class test_func1(unittest.TestCase):
...
When I run test.py I get the message:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "...test.py, line 5, in <module>
from code.app import App
ImportError: No module named 'code.app': 'code' is not a package
After verifying that __init__.py was present and banging my head for a while, on a whim I changed the name of the app directory from code to prog:
import os, sys, unittest
sys.path.insert(1, os.path.join(sys.path[0],'..'))
from prog.app import App
... and everything was suddenly fine. Unittest imported my app properly and ran the tests.
I've searched through https://docs.python.org/3.5/reference/lexical_analysis.html#keywords and https://docs.python.org/3/reference/import.html#path-entry-finders and don't see any indication that code is an illegal directory name. Where would this be documented, and what other directory names are reserved?
System: python 3.4.3 [MSC v1600 32 bit] on win32, Windows 7

code isn't reserved, but it is already defined in the standard library, where is it a regular module and not package. To import from your package, you should use a relative import.
from .code.app import App

Related

Distinguish local module with installed module

I installed django python module on my machine, and used it like this
a.py:
import django.core
...
then, I created an new file django.py in the same folder of file a.py, and re-run a.py, it throw import error, since it just imported my local django.py
File "a.py", line 1, in <module>
import django.core
ImportError: No module named core
So, how to distinguish them when importing python module?
You can use the imp module to import your script directly from a local path:
mymodule = imp.load_source('mymodule', 'django.py')
You can then use mymodule as if you had imported it normally.
Use caution, however; the python import internals must be subverted responsibly.
You could temporarily remove the current directory from PYTHONPATH:
$ python -c'import numpy.core' # works
$ touch numpy.py # add conflicting module
$ python -c'import numpy.core' # it fails now
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'numpy.core'; 'numpy' is not a package
$ python -c'import sys; sys.path.remove(""); import numpy.core' # works again
Needless to say, you should use such hacks sparingly if at all -- avoid manipulating sys.path manually. Rename your local module, to avoid the conflict instead (move it inside a package at least e.g.: your_package/numpy.py).

ImportError: No module named util.dtree_util

I get this error when loading a file using cPickle.
Directory tree:
/qanta/preprocess/dparse_to_dtree.py
/qanta/qanta.py
/qanta/util/dtree_util.py
main.py
extract_data.py
main.py imports extract_data.py
extract_data.py imports dparse_to_dtree.py
A function in dparse_to_dtree.py cPickle dumps a dtree object which is defined in dtree_util.py
then from Main.py a subprocess calls qanta.py to execute but there I get the error:
Traceback (most recent call last):
File "qanta/qanta.py", line 142, in <module>
cPickle.load(open(args['data'], 'rb'))
ImportError: No module named util.dtree_util
What is going wrong here?
You also need to add a __init__.py file. See this question.
Not very nice but adding
import sys
sys.path.append('./qanta/util')
and importing with from ... import * solved the problem

importing a file as a package - Python

I have the following directory structure:
/testlib
__init__.py
ec2.py
unit/
__init__.py
test_ec2.py
utils/
__init__.py
I'm trying to create a unittest class for ec2.py:
import ec2
class TestEC2(unittest.TestCase):
def setUp(self):
self.ec2obj = ec2.EC2(name="testlib_unittest")
if __name__ == '__main__':
unittest.main()
However, when I execute test_ec2.py I'm getting the following error:
python unit/test_ec2.py
Traceback (most recent call last):
File "unit/test_ec2.py", line 4, in <module>
import ec2
ImportError: No module named ec2
I still don't understand why I'm getting that, since I have the __init__.py properly set in the directory. The __init__.py files are completely empty: I've created them with touch __init__.py. Any clues?
**** Updates ****
Here are some suggestions:
/testlib# python unit/test_ec2.py
Traceback (most recent call last):
File "unit/test_ec2.py", line 4, in <module>
from ..ec2 import EC2
ValueError: Attempted relative import in non-package
testlib# python unit/test_ec2.py
Traceback (most recent call last):
File "unit/test_ec2.py", line 4, in <module>
import testlib.ec2 as ec2
ImportError: No module named testlib.ec2
It can't find the module because you're running the script incorrectly. Run the following in testlib/:
python -m unit.test_ec2
Python is not looking for files in directories above yours. Ignacio's answer is correct, and see this for elaboration.

Import http.client encouter import error with Python 3.4.1

I am following the example from the python online document(21.12.3) for practice. When I try to run my script with Run Module(F5), I always get an import error. But if I type them directly into IDLE command line, python does not complain. I am not sure what am I doing wrong.
The python version I am using is
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
The script is
import http.client
conn = http.client.HTTPConnection("192.168.1.2", 8080)
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print(r1.status, r1.reason)
conn.close()
The error message is
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\User\Downloads\http.py", line 1, in <module>
import http.client
File "D:\User\Downloads\http.py", line 1, in <module>
import http.client
ImportError: No module named 'http.client'; 'http' is not a package
You probably have created a Python script and named it http.py in local directory. This conflicts with Python 3's builtin module with the same name and leads to this error. Quick solution is to rename your file to something less generic to avoid conflict with Python builtin modules.
But if you insist, you can clear the name ambiguity by fully qualifying the local python module name using absolute imports:
from . import http
or less confusingly:
from . import http as myhttp
or
from .http import something
On Python 2, it is necessary to enable the absolute import feature at the very top of the importing module using a future statement before using this feature:
from __future__ import absolute_import
I had the same problem. In my case, there was another file named http.py in the same folder. I just renamed it, problem solved.

Strange Python Import Error

I am new to Python. I am getting ImportError and seem to have tried everything that's in the documentation and the various notes in this site and other
My code is structured as follows:
vsm
|
|______bin
| vsmx.py
|______site-packages
__init__.py
|
|_____libs
__init__.py
monitor.py
In monitor.py I have a function named getStr and the two __init__.py files are empty
I have the PYTHONPATH set to vsm/site-packages & vsm/site-packages/libs. When I run from command line, python bin/vsmx.py, I get:
Traceback (most recent call last):
File "bin/vsmx.py", line 15, in <module>
from libs.monitor import getStr
File "/var/src/vsm/bin/vsmx.py", line 15, in <module>
from libs.monitor import getStr
ImportError: No module named monitor
However, when I try to run this interactively, it seems to work. I tried on both windows and linux using python 2.6.1.
Any pointers will be much appreciated
ImportError: No module... is usually a very (obscure) error meaning that you have circular imports.
Module a.py:
import b
Module b.py:
import a
Then main.py:
import a
This should cause ImportError: No module named a, because a is importing b and not ready when b tries to import it.

Categories