12

I am attempting to create a package (mypackage) that contains a few classes, but would like the classes contained in multiple files.

For example, I want class_a.py to contain a class named ClassA, etc...

Thus, I would like the following file structure:

  .../mypackage 
       __init__.py
       class_a.py
       class_b.py
       ...

However, I would like to load and use the package as follows:

load mypackage
a = mypackage.ClassA()

What do I need to do (I assume in the __init__.py) file to make this possible. Currently, it operates using "mypackage.class_a.ClassA()"?

slaughter98
  • 1,759
  • 14
  • 20

3 Answers3

5

As mentioned, in your __init__.py for a class, use the following:

from class_a import ClassA
from class_b import ClassB

for the case of a file without a class, use the following:

from . import file_a
from . import file_b

or if you only want to expose specific methods of a file:

from .file_a import method_a
from .file_b import method_b
Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57
1

Make your __init__.py import all your ClassA, ClassB, etc from other files.

Then you'll be able to import mypackage and use mypackage.ClassA, or from mypackage import ClassA and use it as unqualified ClassA.

A bit of background.

An import foo statement looks for foo.py, then for foo/__init__.py, and loads the names defined in that file into the current namespace. Put whatever you need to be "top-level" into __init__.py.

Also, take a look at __all__ top-level variable if you tend to from mypackage import *.

9000
  • 39,899
  • 9
  • 66
  • 104
  • 4
    Or better yet, never ever use `from mypackage import *`, ever, under any circumstances. – Henry Keiter May 07 '13 at 18:08
  • @HenryKeiter I agree because it's quite annoying when you go through some code looking where you defined something, but then you realize it came with the package that you imported. – programmerpremium Apr 09 '20 at 08:40
-1

In your __init__.py, add this:

from class_a import ClassA
from class_b import ClassB

del class_a
del class_b
Andenthal
  • 849
  • 5
  • 13