Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - import subpackage from a package not working?

I have the following files:

pack/__init__.py
pack/subpack/__init.__py
pack/subpack/mod2.py

And the following code fails on the last line:

from pack import * #should import everything
print subpack      #NameError: name 'subpack' is not defined

I would expect the subpackage to be imported - why is there a difference, and how can I overcome it? Important: by "overcoming" I mean being able to refer to subpack without needing to write pack.subpack all the time.

like image 798
olamundo Avatar asked Feb 17 '26 18:02

olamundo


2 Answers

You need to add

__all__ = ["mod1", "subpack"]

to pack/__init__.py. Without this line, mod1 would not be imported either, so I wonder what is going on there. See also the relevant section in Guido's tutorial.

like image 120
Sven Marnach Avatar answered Feb 19 '26 06:02

Sven Marnach


Try adding "import subpack" in pack/__init__.py

If you have __all__ declared, make sure 'subpack' appears there.

like image 29
bukzor Avatar answered Feb 19 '26 07:02

bukzor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!