Reputation: 3924
The Python standard library has functions designed to be imported and used simply. for example:
import re
m = re.search('foo')
The package documentation https://docs.python.org/3/tutorial/modules.html#packages has an example subpackage layout. But let's simplify that to have only a single package with no subpackages:
sound/ Top-level package
__init__.py Initialize the sound package
wavread.py
wavwrite.py
...
Our hypothetical wavread.py defines a function:
def read_wav(name):
return 'Hello ' + name
Functions in this package are called with:
for example:
import sound.wavread
sf = sound.wavread.read_wav('foo')
or:
import sound.wavread as sound
sf = sound.read_wav('foo')
Question: How should one create a package so that it can be both imported and used simply, without exposing python filenames (e.g., wavread
) to the package user? One could create a "package" that is a single file containing all of its functions, but one huge file isn't very modular. What is the Pythonic way to structure a complex package for both ease of use and ease of maintenance?
Desired user code:
import sound
sf = sound.read_wav('foo')
Upvotes: 1
Views: 47
Reputation: 3323
in __init__.py
do the following:
from .wavread import * #or only the functions you want to export from wavread.py
from .wavwrite import *
# and so on for all files that implement function of the sound module
This way user of sound module can do:
from sound import *
or from sound import read_wav
or
import sound
# ...
sf = sound.read_wav('foo')
Upvotes: 4