Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Classes in Packages

I'm learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a package is to define them in the __init__.py of that package. Coming from Java, I'd kind of like to define individual files for my classes. Is this a recommended practice?

I'd like to have my directory look somewhat like this:

recursor/
    __init__.py
    RecursionException.py
    RecursionResult.py
    Recursor.py

So I could refer to my classes as recursor.Recursor, recursor.RecursionException, and recursor.RecursionResult. Is this doable or recommended in Python?

like image 582
Naftuli Kay Avatar asked Jun 11 '10 16:06

Naftuli Kay


2 Answers

Go ahead and define your classes in separate modules. Then make __init__.py do something like this:

from RecursionException import RecursionException
from RecursionResult import RecursionResult
from Recursor import Recursor

That will import each class into the package's root namespace, so calling code can refer to recursor.Recursor instead of recursor.Recursor.Recursor.

I feel the need to echo some of the other comments here, though: Python is not Java. Rather than creating a new module for every class under the sun, I suggest grouping closely related classes into a single module. It's easier to understand your code that way, and calling code won't need a bazillion imports.

like image 160
ʇsәɹoɈ Avatar answered Sep 24 '22 00:09

ʇsәɹoɈ


This is perfectly doable. Just create a new class module for each of those classes, and create exactly the structure you posted.

You can also make a Recursion.py module or something similar, and include all 3 classes in that file.

(I'm also new to Python from Java, and I haven't yet put anything in my __init__.py files...)

like image 45
froadie Avatar answered Sep 25 '22 00:09

froadie