简体   繁体   中英

ImportError with absolute and relative imports

Having trouble importing with a very simple file structure.

My file structure looks like this:

project/
  ...
  project.py
  helper.py
  __init__.py
  ...

Within project.py is the class I am trying to import in helper

#project.py

class MyAPIOne():
...

class MyAPITwo():
...

#helper.py

import MyAPIOne

if __name__ == "__main__":
  api = MyApiOne()
  ...

When running with python3 helper.py :

If I keep the absolute import import MyAPIOne I recieve ModuleNotFoundError: No module named 'MyAPIOne'

If I change it to a relative import from. import MyAPIOne from. import MyAPIOne I receive ImportError: cannot import name 'MyAPIOne'

I have also experimented with appended to sys.path various directories, with no luck.

If you are running this script from the project folder, you can alter your import the following way: from project import MyAPIOne . Also, you can add this folder to your PYTHONPATH env variable.

Upd: to add some folder to PYTHONPATH you can ran

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

main file can import all the files, but main file can't be imported by other files.

once file mentioned with __name__ = "__main__" , then it becomes main file. so helper.py is acts as main file. it can't be imported.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM