Shenpai Yajulight
Shenpai Yajulight

Reputation: 53

How can I place all symbols exported from a Python package at the package scope?

A couple of months ago, I happened to use BeautifulSoup in some Python project and I noticed the library was organized in a somewhat unique manner.

In order to use the BeautifulSoup class you only have to import the top-level package, like this:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)

I knew that it was because the BeautifulSoup class, which is basically the only class provided by the library, is directly placed in __init__.py within the bs4 directory with the clear intent to make importing the library simple.

I wondered if such practice is considered appropriate when I build my own library.

Obviously placing classes at the package scope by writing the class body in __init__.py will inflate the file indefinitely, but I do not either like the usual Python way in which there is usually only one class (or whatever unit of code) per module.

In short, I do not like to write redundant import statements like this, which seems inevitable when placing one class per module:

from mylibrary.splendidparser import splendidparser
from mylibrary.supremetimer import supremetimer
from mylibrary.superbrenderer import superbrenderer

And instead, I prefer the BeautifulSoup way:

from mylibrary import splendidparser
from mylibrary import supremetimer
from mylibrary import superbrenderer

Is there any way I can package my library to enable this importing style without inflating __init__.py?

Upvotes: 1

Views: 141

Answers (1)

gilch
gilch

Reputation: 11681

You don't have to put the implementation in __init__.py. You can put the definitions in other modules inside the package directory and then just import them in __init__.py and they will then be available from there.

Yes, this is appropriate. Try import this and you'll see the Zen of Python, which the community tries to follow, including "Flat is better than nested."

Upvotes: 3

Related Questions