Home > Net >  What is the preferred way of importing object hierarchies into Python
What is the preferred way of importing object hierarchies into Python

Time:09-23

I create a class Animal in a file animal.py

class Animal():
    pass

I create a child class Dog in file dog.py

from animal import Animal

class Dog(Animal):
    pass

If I run dog.py now, everything works.

Because these two classes are so incredibly useful, I now want to use them in my new project.

So I create a subfolder ./lib in my new project and copy the two files in here.

ProjectFolder:

  • main.py
  • lib/
    • animal.py
    • dog.py

Now want to use the Dog class in my main.py.

from lib.dog import Dog

sparky = Dog()

Aaand it doesn't work anymore because the Dog class can't find its Animal parent class. I guess because in sys.path[0] is now the path of main.py.

What is the correct approach here?

The two files animal.py and dog.py should of course work in every new project without having to adapt them every time.

CodePudding user response:

You will start organizing your code into modules and packages: you already have the modules which are your .py, and you will create packages based on your directories to use to import the modules you want. The official python modules and packages doc will help you a lot with this.

For your case a good place to start is to setup a main package and then a package for your lib:

main-package/
   __init__.py
   main.py
   lib/
      __init__.py
      animal.py
      dog.py
  • The __init__.py can be empty, it is just required so that Python understands that the directory that contains it is a package. We are saying that both the main-module and the lib are packages.
  • With the main-module as package whenever you add a sibling directory to lib you can import directly with from main-package.lib.dog import Dog, which is called an absolute import
  • If you keep the main.py at the main package level like it is on my example above you can keep doing like you are currently with from lib.dog import Dog, since they are within the same package
  • Now you should be able to import animal from dog with: from lib.animal import Animal or from .animal import Animal

Another reference: the import system python docs.

Hope that helps.

  • Related