How do I import from a higher level directory in python?
For example, I have:
/var/www/PROJECT/subproject/_common.py
/var/www/PROJECT/subproject/stuff/routes.py
I want to import variable A in _common.py to routes.py
# routes.py
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from _common import A
but I get the error:
ImportError:cannot import name 'A'
Change file directory:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),"../../project")))
from _common import A
OLD VERSION
To solve the issue replace ".." with os.pardir:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
from _common import A
NEW VERSION
The code above does not solve the problem in the question because the true problem lies in the project structure not in the particular line. The problem is circular import. The problem became clear after the full traceback has been provided. Here is the simple way to reproduce the issue - consider 3 files...
main.py:
import a
a.py:
import b
A = 'A'
b.py:
from a import A
... the error is:
ImportError: cannot import name 'A'
OR
b.py:
import a
BB = a.A
... the error is:
AttributeError: module 'a' has no attribute 'A'
The solution to the problem has been discussed many times - search on SO
Related
below the folder structure of my software:
below the code of all the .py files:
run.py:
import modules.module_01.aa as a
a.test()
# test:
if __name__=="__main__":
pass
aa.py (module 1):
import libraries.qq as q
import libraries.zz as z
def test():
q.qq_fun()
z.zz_fun()
print("ciao")
qq.py (library used by aa.py):
def qq_fun():
pass
zz.py (library used by aa.py):
def zz_fun():
pass
my question is really simple, why when I run "run.py" Python say to me:
why "aa.py" can't import the module "qq.py" and "zz.py"? how can I fix this issue?
run.py
In run.py, the Python interpreter thinks you're trying to import module_01.aa from a module named module. To import aa.py, you'll need to add this code to the top of your file, which adds the directory aa.py is in to the system path, and change your import statement to import aa as a.
import sys
sys.path.insert(0, "./modules/module_01/")
aa.py
The same problem occurs in aa.py. To fix the problem in this file, you'll need to add this code to the top of aa.py, which adds the directory qq.py and zz.py are in, and remove the libraries. from both of your import statements.
import sys
sys.path.insert(0, "./modules/module_01/libraries")
e.g.
import os as my_os
import my_os.path
ModuleNotFoundError: No module named 'my_os'
but the following script is ok
import os
import os.path
You can't do that in Python.
import statements are importing from Python file names.
You aren't renaming the file of os to my_os, therefore this wouldn't work.
As mentioned in the documentation:
The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.
Tried the similar way as os.py did:
import json as my_json
from my_json.decoder import * # ModuleNotFoundError: No module named 'my_json'
import sys
import json.decoder as my_decoder
sys.modules['my_json.decoder'] = my_decoder
from my_json.decoder import * # it's ok now
I have a package structure like this:
- src
- src/main.py
- src/package1
- src/package1/__init__.py
- src/package1/module1.py
- src/package1/module2.py
... where module2 is a subclass of module1, and therefore module1 gets referenced by an absolute import path in module2.py.
That is, in src/package1/module2.py:
from package1.module1 import SomeClassFromModule1
The problem occurs in the main.py script:
## here the imports
def main():
# create an instance of the child class in Module2
if __name__ == "__main__":
main()
Option 1 works. That is, in src/main.py:
from package1.module2 import SomeClassFromModule2
some_name = SomeClassFromModule2()
Option 2 does not work. That is, in src/main.py:
import package1.module2.SomeClassFromModule2
some_name = package1.module2.SomeClassFromModule2()
... causes the following error.
ModuleNotFoundError: No module named 'package1.module2.SomeClassFromModule2'; 'package1.module2' is not a package
So why is there this difference between the import and from ... import idiom?
Would be glad for some clarification.
import x keyword brings all the methods and class from x in the the file it is being called.
from x import y this brings a specific method or class('y' is a method or class) from that .py file ('x' is the file here) instead of bringing all the methods it has.
In your case when you import package1.module2 the SomeClassForModule2() is being already imported and hence you need not write import package1.module2.SomeClassFromModule2
here I guess you want to access a class, so you need to create a object in order to access it.
hope this helped you
After some test, I think you cannot import a function or class by using import your_module.your_class.
It's all about package, module, function and class:
# import module
>>>import os
<module 'os' from ooxx>
#use module of module (a litte weird)
>>>os.path
<module 'posixpath' from ooxx>
#import module of module (a litte weird)
>>>import os.path
#use function
>>>os.path.dirname
<function posixpath.dirname(p)>
# you cannot import a function (or class) by using 'import your.module.func'
# 'import ooxx' always get a module or package.
>>>import os.path.dirname
ModuleNotFoundError
No module named 'os.path.dirname'; 'os.path' is not a package
# instead of it, using 'from your_module import your_function_or_class'
>>>from os.path import dirname
<function posixpath.dirname(p)>
I'm having an issue with the import statement in Python 3. I'm following a book (Python 3 Object Oriented) and am having the following structure:
parent_directory/
main.py
ecommerce/
__init__.py
database.py
products.py
payments/
__init__.py
paypal.py
authorizenet.py
In paypal.py, I'm trying to use the Database class from database.py. So I tried this:
from ecommerce.database import Database
I get this error:
ImportError: No module named 'ecommerce'
so I try with both of these import statements:
from .ecommerce.database import Database
from ..ecommerce.database import Database
and I get this error:
SystemError: Parent module '' not loaded, cannot perform relative import
What am I doing wrong or missing?
Thank you for your time!
Add your parent_directoryto Python's search path. For example so:
import sys
sys.path.append('/full/path/to/parent_directory')
Alternatively, you can add parent_directory to the environmental variable PYTHONPATH.
I have a module that I am testing that depends on another module that won't be available at the time of testing. To get around this, I wrote (essentially):
import mock
import sys
sys.modules['parent_module.unavailable_module'] = mock.MagicMock()
import module_under_test
This works fine as long as module_under_test is doing one of the following import parent_module, import parent_module.unavailable_module. However, the following code generates a traceback:
>>> from parent_module import unavailable_module
ImportError: cannot import name unavailable_module
What's up with this? What can I do in my test code (without changing the import statement) to avoid this error?
Alright, I think I've figured it out. It appears that in the statement:
from parent_module import unavailable_module
Python looks for an attribute of parent_module called unavailable_module. Therefore, the following set up code fully replaces unavailable_module within parent_module:
import mock
import sys
fake_module = mock.MagicMock()
sys.modules['parent_module.unavailable_module'] = fake_module
setattr(parent_module, 'unavailable_module', fake_module)
I tested the four import idioms of which I am aware:
import parent_module
import parent_module.unavailable_module
import parent_module.unavailable_module as unavailabe_module
from parent_module import unavailable_module
and each worked with the above set up code.