Joe Gavin Joe Gavin - 2 years ago 93
Python Question

Error converting module to a package

I have a module of helper functions which is getting long and tedious to maintain. I'd like to break it into a simple package. My package directory is defined on PYTHONPATH, and looks like this:

test/ <---this is empty

This is imported in the usual way (import test) but upon inspection (dir(test)) the library does not contain the modules a or b, just some top level attributes including the correct path to the subdirectory. The directory above also includes a pycache indicating that python has found it and built the bytecode. Sorry for such a newbie question but I could use a hint what is going wrong. thanks!

Solution from below: the init file now contains

import test.a
import test.b

My intent was to have each helper script as its own module, leading to perhaps many small modules that are easy to find and maintain. Is this idiomatic? inefficient? I get the maintenance implications to the init file. Any experience or best practices to share? thanks.

Answer Source

You should also import a and b from the package in order for dir to list them. If you want to auto import modules in a package when importing a package, specify in by adding import statements of the modules you want to import in

Edit: As long as different modules serve different purposes, its better to keep all the related helpers in their own module. All the modules that you want to import by default when your package is imported should be specified in the file. Others can be imported whenever necessary. There shouldn't be any performance implications even if you import a module multiple times they are initialized only once as found here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download