I am developing a Python package for dealing with some scientific data. There are multiple frequently-used classes and functions from other modules and packages, including numpy, that I need in virtually every function defined in any module of the package.
What would be the Pythonic way to deal with them? I have considered multiple variants, but every has its own drawbacks.
Import the classes at module-level with
from foreignmodule import Class1, Class2, function1, function2
Then the imported functions and classes are easily accessible from every function. On the other hand, they pollute the module namespace makingdir(package.module)
andhelp(package.module)
cluttered with imported functionsImport the classes at function-level with
from foreignmodule import Class1, Class2, function1, function2
The functions and classes are easily accessible and do not pollute the module, but imports from up to a dozen modules in every function look as a lot of duplicate code.Import the modules at module-level with
import foreignmodule
Not too much pollution is compensated by the need to prepend the module name to every function or class call.Use some artificial workaround like using a function body for all these manipulations and returning only the objects to be exported... like this
def _export(): from foreignmodule import Class1, Class2, function1, function2 def myfunc(x): return function1(x, function2(x)) return myfunc myfunc = _export() del _export
This manages to solve both problems, module namespace pollution and ease of use for functions... but it seems to be not Pythonic at all.
So what solution is the most Pythonic? Is there another good solution I overlooked?
import foreignmodule
. - Manny D