How to setup relative import in python?

Viewed 94

My project tree is as simple as:

test
  ├── __init__.py (has line: "foo = True")
  ├── bar.py (has line: "bar = False")
  └── test.py (has line: "from . import foo; from .bar import bar")

But none of the imports in test.py work. When I run python test.py, it returns: attempted relative import with no known parent package

Did I miss anything here? I am using python 3.7.6

4 Answers

the issue is arising because you are trying to import foo from __init__.py file as from . import foo , but to import from __init__.py file you need to use a parent folder module, ie from test import foo as how it is structured to import from __init__.py.

Your code is fine, but the test file needs to be imported as part of a package. So I created the following files and directories, exactly how you explained:

.
└── test
    ├── bar.py
    ├── __init__.py
    ├── __pycache__
    └── test.py

From the parent of test, I ran this:

>>> import test
>>> import test.test
>>> import test.bar
>>> 

It worked fine. But if you're doing relative imports, the code you're importing needs to be imported as part of a package, not executed as a standalone script.

If you're going to import files from the same folder you are, just use their file names:

bar.py

bar = False

foo.py

foo = True

test.py

from foo import foo
from bar import bar

print(foo, bar)

Running python test.py returns:

True False

Following the same/similar file structure, I can think of 2 ways to do imports:

  1. Use absolute import if all three files are in the same directory level, so test.py should look like:

    import foo
    import bar
    

    and python test.py should run fine from the test directory.

  2. Move foo.py and bar.py into a new directory, let's call it package, so the structure will be changed now to:

    test/
    ├── package
    │   ├── bar.py
    │   └── foo.py
    └── test.py
    

    And test.py will be:

    from package import bar
    from package import foo
    

    python test.py from the test directory will work.

Related