0

I'm tired of reading one-off use cases of relative imports so I figured I'd as a question to get an example of how to do a relative import from a directory above and bellow, for both importing module functions and class objects.

directory structure:

.
├── lib
│   ├── __init__.py
│   └── bar.py
└── src
    ├── main.py
    └── srclib
        ├── __init__.py
        └── foo.py

bar.py

def BarFunc():
        print("src Bar function")

class BarClass():
        def __inti__(self):
                print("src Bar Class")
        def test(self):
                print("BarClass working")

foo.py

def FooFunction():
        print("srclib Foo function")

class FooClass():
        def __init__(self):
                print("srclib Foo Class")
        def test(self):
                print("FooClass working")

Question: What is the syntax in python 3 to import for these use cases?

main.py

# What is the syntax to import in python 3?

# I want to be able to call FooFunc()
foo.FooFunc()

# I want to be able to create a FooClass() object
foo_class = foo.FooClass()
foo_class.test()

# I want to be able to call FooFunc()
bar.BarFunc()

# I want to be able to create a BarClass() object
bar_class = bar.BarClass()
bar_class.test()
Alexander Kleinhans
  • 5,950
  • 10
  • 55
  • 111
  • 2
    Relative imports are not about directories. They are not a directory traversal mechanism; they only say which thing to import, not where in the file system that thing is located. – user2357112 Dec 11 '17 at 01:54
  • Okay. I did not know that. I'm still wondering how I would import my lib files from main given my directory structure though. – Alexander Kleinhans Dec 11 '17 at 01:57
  • You cannot actually perform relative imports in `main.py` at all, as it is not part of a package. – user2357112 Dec 11 '17 at 01:57
  • It's impossible to import `lib.bar` in common as your top module is `main`, and `lib` is beyond top module. But you can use `sys.path.append` to add that directory or set env variable `PYTHONPATH`. Both of them are not recommended. – Sraw Dec 11 '17 at 01:58
  • Are you sure you mean `def __inti__(self):` ? – Mr_and_Mrs_D Dec 11 '17 at 11:41
  • 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

0

It all depends on where you start your python interpreter from. In your case, I would suggest you to start the interpreter from your project's root directory while making the following changes:

In file src/srclib/__init__.py add:

from . import foo

The reason for doing this is to explicitly state in your __init__.py file what to import from your module.

In your main.py file, add the following:

from lib import bar
from src.srclib import foo

Hope this helps!

TerminalWitchcraft
  • 1,732
  • 1
  • 13
  • 18