Search code examples
pythonpython-3.xpython-importrelative-path

Relative import in Python 3.6


I want to use relative import in Python 3.

My project:

main_folder
  - __init__.py
  - run.py
  - tools.py

I want to have in run.py (MyClass declared in __init__.py):

from . import MyClass

And in run.py:

from .tools import my_func

An ImportError is raise.

Alternatively, with absolute import, debugging in PyCharm does not work and the library takes from installed packages, not my directory.

I know one way, but it is terrible:

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

How to use this import in my project?


Solution

  • When you use PyCharm, it automatically makes the current module main, so relative statements like from . import <module> will not work. read more here.

    to fix your problem, put the __init__.py and tools.py files in a sub-directory

    main_directory/
        run.py
        sub_directory/
            __init__.py
            tools.py
    

    in your run.py file, write the following as your import statements

    from sub_directory import tools
    from sub_directory.__init__ import MyClass
    

    Edit: as @9000 mentioned, you can write from sub_directory import MyClass and achieve the same thing.