0

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?

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • What is the PyCharm working directory in the configuration of that run? – Javier Feb 22 '18 at 15:53
  • If you're in the directory which contains `main_folder` you can call `import main_folder.run` just fine – Steve Feb 22 '18 at 16:07
  • Does this answer your question? [Python3 correct way to import relative or absolute?](https://stackoverflow.com/questions/28400690/python3-correct-way-to-import-relative-or-absolute) – Ani Menon Jul 03 '20 at 05:09

1 Answers1

1

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.

Joshua Yonathan
  • 490
  • 1
  • 5
  • 16
  • 1
    `from sub_directory.__init__ import MyClass` is awkward; the same effect is achieved by just `from sub_directory import MyClass`. – 9000 Feb 22 '18 at 16:14