python absolute import of submodule fails - python

I have seen other posts but did not find answer that worked!
File structure
my_package/
__init__.py -- empty
test/
__init__.py -- empty
test1.py
Fail
from my_package import test
test.test1
gives
AttributeError: 'module' object has no attribute test
Following Passes
from my_package.test import test1
# or
import my_package.test.test1
from my_package import test
# now this works
test.tes1
<module 'my_package.test.test1' from ...
I have
from __future__ import absolute_import
in all files, and using python2.7

When you import a package (like test), the modules (like test1) are not automatically imported (unless perhaps you put some special code to do so in __init__.py). This is different from importing a module, where the contents of the module are available in the modules namespace. Compare with the Python standard library's xml.etree.ElementTree module:
>>> import xml
>>> xml.etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> from xml import etree
>>> etree.ElementTree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> from xml.etree import ElementTree
>>> ElementTree.ElementTree
<class 'xml.etree.ElementTree.ElementTree'>

Related

Import Error when trying to make python 2 modul

This doesn't seem to be an issue in python 3 but I'm needing to use python 2.7 for this and get the following issue
DIRECTORY STRUCTURE
module
├── __init__.py
└── submodule
├── __init__.py
└── test.py
# module/__init__.py
from module import submodule
# module/submodule/__init__.py
from module.submodule import test
# module/submodule/test.py
from module import submodule
when I try to import module from somewhere else it results in the following error:
>>> import module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "module/__init__.py", line 1, in <module>
from module import submodule
File "module/submodule/__init__.py", line 1, in <module>
from module.submodule import test
File "module/submodule/test.py", line 1, in <module>
from module import submodule
ImportError: cannot import name submodule
I'm assuming the issue has something to do with circular imports but i need to use submodule in both module/__init__.py and module/submodule/test.py
any help is appreciated
As you've mentioned circular imports, one way to resolve this is by importing the module locally.
For e.g.
def fun():
from module import submodule

What does 'from dot import asterisk' do in Python 3?

Question
What does the following line do in Python 3?
>>> from . import *
What I found out so far...
It does not output anything and the only change I can see in Python 3.7.3 is the following:
>>> '__warningregistry__' in locals()
False
>>> from . import *
>>> '__warningregistry__' in locals()
True
>>> locals()['__warningregistry__']
{'version': 0}
This might be part of the warnings module and indicates that there is a warning somewhere which is not printed, but the documentation mentions only a variable __warningregistry__ in the the module warnings.
The documentation explains how from . import foo works, and how from bar import * works, but I couldn't find anything about from . import *. One might expect that all names from __init__.py are loaded into the current name space (as from bla import * would do for bla.py) but this doesn't seem to be the case and also it doesn't make sense when __name__ == '__main__' (scripts and terminal).
Python 2 behaves more similar to what I had expected:
>>> # Python 2.7.16
>>> from . import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
PEP 328 is quite illuminative but doesn't answer my question either.
When __main__ is a script or interactive session, . is the __main__ package itself:
$ python3 -c 'from . import float'
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name 'float' from '__main__' (unknown location)
This makes from . import * a noop, with __warningregistry__ added as a side-effect of the import machinery.
Relative imports from __main__ were special-cased by PEP 366. This introduced __package__ for relative package name lookup, and specifies that __main__. __package__ has the special value None.
In addition, the module import spec __main__.__spec__ may be None - namely in an interactive shell or when executing a script.
As it turns out, any module with __package__ = __spec__ = None will treat . as itself:
$ cat test.py
__package__ = __spec__ = None
from . import float
$ python3 -c 'import test'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/mfischer/PycharmProjects/lispy/test.py", line 2, in <module>
from . import float
ImportError: cannot import name 'float' from 'test' (./test.py)
The __warningregistry__ is added because there is a hidden warning from the missing attributes. It is suppressed by default, but you can see it with all warning enabled:
$ python3 -Wa -c 'from . import float'
-c:1: ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name 'float' from '__main__' (unknown location)

AttributeError: 'module' object has no attribute 'TestCase'

I have file with unittest named: test.py
My code:
import unittest
class Test(unittest.TestCase):
def myTest(self):
a = 1
self.assertEqual(a, 1)
if __name__ == '__main__':
unittest.main()
When I press F5, I get an error:
Traceback (most recent call last):
File "/home/mariusz/Pulpit/test.py", line 1, in <module>
import unittest
File "/home/mariusz/Pulpit/unittest.py", line 3, in <module>
AttributeError: 'module' object has no attribute 'TestCase'
You have a local file named unittest.py that is being imported instead:
/home/mariusz/Pulpit/unittest.py
Rename that file or remove it altogether. Make sure you remove any corresponding unittest.pyc file in the same folder if it is there.
The file is masking the standard library package.
Your script named unittest.py is replacing the module file.
Rename your unittest.py script to something else.
In my case, one of the dependency was not there.
import os
from some_package import some_module
the some_module was not there in python(python couldn't import it). Once I commented the import statement python started discovering my test cases.
python -m unittest tests.test_my_own_module

How can you find where python imported a particular module from?

How can you find where python imported a particular module from?
Each module object has a __file__ attribute:
import module
print module.__file__
Some modules are part of the Python executable; these will not have the attribute set.
Demo:
>>> import urllib2
>>> urllib2.__file__
'/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.pyc'
>>> import sys
>>> sys.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
You could also run Python in verbose mode, with the -v command line switch or the PYTHONVERBOSE environment variable; Python then prints out every imported file as it takes place.

How to mock python module in unittest

I have a problem when mocking in unittest.
#!/usr/bin/env python
import sys
sys.modules["foo.Bar"] = __import__("mock_bar")
import foo.Bar
print foo.Bar.__name__
I've got an ImportError exception in line 4. I don't know why since I have do some mock at line 3. There is a reference of how to mock import here.
Here's the error message:
Traceback (most recent call last):
File "test.py", line 4, in <module>
import foo.Bar
ImportError: No module named foo.Bar
"import foo.Bar" should equal to "__import__('foo.Bar')", and before that I've hacked sys.modules to pretend module 'foo.Bar' has been already imported. Why python still try to import foo.Bar and complain?
Try doing import foo before your __import__ line: I think it could help.

Categories

Resources