Error with Import in python from the same folder - python

I have three files in folder
exceptions.py
class MyException(Exception):
pass
MyClass.py which begins as:
from exceptions import MyException
And empty __init__.py
When I'm trying to import MyClass.py there is Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "MyClass.py", line 1, in <module>
from exceptions import MyException
ImportError: cannot import name MyException
I've read docs and a lot of articles but can't find what's wrong

There is a standard built-in module named exceptions which is imported instead of your exceptions.py.
You can either rename your exceptions.py or use dotted import:
from .exceptions import MyException
See https://docs.python.org/2/tutorial/modules.html#intra-package-references for more.

You can't use the name exeptions.py as there already exists a module named exeptions, which has no class named Myexeption, so you are getting thus error. Just change the file name and you will be all right.

Related

Python ImportError Cannot Import Name

In my working folder I have a file called exceptions.py, which contains only:
class ParseException(Exception):
pass
class QueryException(Exception):
pass
In the same folder I have a file, lets call it my_script.py
In my_script.py, when I do from exceptions import ParseException I get an error:
ImportError: cannot import name ParseException
I cannot figure out what's going on here. I've never seen this error before, and when I looked it up I mainly see problems with circular dependencies, but I don't have any here...
There is the exceptions module in your Python library which doesn't have the methods/classes you're trying to import. Change your file name to something different and it'll work.
Try the following yourself
>>> import exceptions
# Works OK
>>> from exceptions import ParseException
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name ParseException
>>> from exceptions import ImportError # Works OK too

ImportError: cannot import name

For some reason I receive an ImportError every time I try to import a class from another file. Here's the github page for my project: https://github.com/wheelebin/mcnextbot
Here's the error that I'm receiving:
Traceback (most recent call last):
File "ircbot.py", line 36, in <module>
from test import mcnextlvl
ImportError: cannot import name mcnextlvl
Here your from test import something refers to the module test in <PYTHONPATH>/lib, not yourselves test.py, and there is no submodule/class mcnextlvl there. You should use from lib.test import mcnextlvl as #sgmart commented.
The __init__.py python file allow you can import your individual modules named 'test' from the lib package.

Module cannot make absolute imports to its own branch in the package tree?

If you have a package structure as this:
foldertest/
__init__.py
a/
__init__.py
asub/
__init__.py
b/
__init__.py
foldertest.__ini__.py:
import a
foldertest.a.__init__.py:
import foldertest.a.asub
print foldertest.a.asub
If I from the folder above foldertest/ run the python shell and issue import foldertest I receive the following error:
>>> import foldertest
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foldertest/__init__.py", line 1, in <module>
import foldertest.a
File "foldertest/a/__init__.py", line 4, in <module>
print foldertest.a.asub
AttributeError: 'module' object has no attribute 'a'
Whereas if I would change foldertest.a.__init__.py to import foldertest.b instead and try printing that I would receive:
>>> import foldertest
<module 'foldertest.b' from 'foldertest/b/__init__.pyc'>
>>>
Am I doing something wrong or is not possible to use absolute referencing to a package's/module's own branch in the package tree? (also PyDev seems to disapprove of writing imports like this) I wanted to have absolute package references for consistency. Also I do not know of any "best practice" for writing import statements or structuring packages that suggest against this.

Why does import error change to "cannot import name" on the second import?

Here's a mysterious python problem:
I'm developing a python package that occasionally reports import errors looking like ImportError: cannot import name …. The modules it cannot import generally
are importable
do not have any circular import issues (that I can detect).
I have been able to reproduce a similar effect with this simple example:
mypkg/__init__.py:
from . import module_a
yarg ## cause import error
mypkg/module_a.py:
print "imported module_a"
Now I will attempt to import the package twice. Notice that the error changes on the second import:
>>> import mypkg
Module A imported
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg/__init__.py", line 2, in <module>
yarg
NameError: name 'yarg' is not defined
>>> import mypkg
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg/__init__.py", line 1, in <module>
from . import module_a
ImportError: cannot import name module_a
What gives?
Note:
the problem goes away if I use an absolute import instead
if I delete the key sys.modules['mypkg.module_a'] after the first import, then the second import gives me back the original error message
I can illustrate what is causing the difference between each import, but I'm not expert enough on Python's import process to be able to explain the why very well.
>>> import sys
>>> before_import = set(sys.modules.keys())
>>> import mypkg
imported module_a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg\__init__.py", line 2, in <module>
yarg ## cause import error
NameError: name 'yarg' is not defined
>>> after_import = set(sys.modules.keys())
>>> after_import.difference(before_import)
set(['mypkg.module_a'])
When you import mypkg, it successfully imports module_a and adds it to sys.modules. Then mypkg errors and doesn't get added itself to the sys.modules dictionary. Deleting the entry allows you to reimport with the same error:
>>> import sys
>>> del sys.modules['mypkg.module_a']
>>> import mypkg
imported module_a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg\__init__.py", line 2, in <module>
yarg ## cause import error
NameError: name 'yarg' is not defined
Now, what I think is happening is:
import mypkg starts the import process for mypkg
As it's processing mypkg, it successfully imports module_a as
a subpackage of itself and adds it to sys.modules
When it hits the error, the import process for mypkg fails and no
entry for mypkg is left in sys.modules
The conjunction of the package failing but the subpackage succeeding
conflicts with subsequent imports
That's about the best I can fathom, sorry. Python's import process is something of a black art.
I'm pretty sure the problem is that your package is failing to load. You've put some nonsense (yarg by itself) in the __init__.py file. This means that mypkg can't be imported. Because of this, mypkg.module_a can't be imported either.
I suspect you get different errors because Python is doing some caching of the module state. The first time you try importing mypkg the import of its submodule module_a is allowed even though mypkg is in the process of being loaded. The second time, the fact that mypkg doesn't work right is cached, so mypkg.module_a fails to load since its parent package is broken.

Python design - cross imports

I'm stuck with imports and don't know how to address the issue.
I have 3 modules:
test_project.py
modules/__init__.py
r.py
module.py
module_configuration.py
The list of dependencies:
test_project.py IMPORTS modules/__init__.py
modules/__init__.py IMPORTS r.py
r.py IMPORTS > module_configuration.py
module_configuration.py IMPORTS > modules/__init__.py
So as you can see, we have a circular import here.
modules/__init__.py keeps dict of class definitions (class like R).
R class makes instance of ModuleConfiguration in its constructor
ModuleConfiguration needs dict of classes from modules/__init__.py.
Error message I get:
ERROR: controller.test_project (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: controller.test_project
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/loader.py", line 252, in _find_tests
module = self._get_module_from_name(name)
File "/usr/lib/python2.7/unittest/loader.py", line 230, in
_get_module_from_name__import__(name)
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/controller/test_project.py",
line 9, in <module>
from c.core.modules import MODULES
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/modules/__init__.py", line 5, in <module>
from R import R
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/modules/R.py", line 6, in <module>
from c.core.module import Module
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/module.py", line 13, in <module>
from c.core.module_configuration import ModuleConfiguration
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/module_configuration.py", line 7, in <module>
from c.core.modules import MODULES
ImportError: cannot import name MODULES
Any ideas on how to solve it?
Instead of making the instances at module load time, implement functions returning the relevant results and keep these functions in their respective modules. Then once the modules are loaded everything is available to all.
There's nothing wrong with importing moduleA from moduleB and moduleB from moduleA.
Do you need module global objects that must be created at module load time? This is usually not needed. Instead try to construct whatever module globals are required at first use once all modules are in place.

Categories