Siva kumar Reddy Siva kumar Reddy - 2 months ago 8
Python Question

how can i control modules in package to import in python?

Consider an example,

I have a package having list of modules:

/mypackage/
__init__.py
mod1.py
mod2.py
mod3.py


prog1.py
: I would like to allow only
mod2
here
prog2
: allow
mod1,2


If I write,

prog1.py
import mypackage
# only mod2 should import

prog2.py
import mypackage
# only mod1,mod3 should import


How can I restrict at package or module level?

Answer

I don't think that packages should control who and how can import them, basically packages should not know about their importers. However if you for some reason still thing this is a good idea, you can get a main filename by:

import __main__
main_file = __main__.__file__

And then modify your

__all__

attribute of module based on a main file name.