With the following dir structure
.
├── setup.py
└── yourpackage
├── __init__.py
├── some_module.py
├── other_module.py
└── sub_package
├── __init__.py
└── more_modules.py
Is it possible to do this:
>> import yourpackage as yp
>> yp.some_module.bar()
>> yp.sub_package.more_modules.foo()
where the contents of some_module is
def bar(): print('bar')
where the contents of more_modules is
def foo(): print('foo')
I can't seem to get this to work
EDIT: The error I would get in the first case is
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: module 'yourpackage' has no attribute 'some_module'
In the second case, it's a similar error, but with more_modules
If you want to use the inner modules without importing them explicitly you have to import them in the __init__.py file:
import some_module
import other_module
import sub_package
and in sub_package/__init__.py:
import more_modules
Note that that might make the first import of the module slower.
Other option is to import them explicitly in your code:
>> import yourpackage.some_module
>> import yourpackage.sub_package.more_modules
>> yourpackage.some_module.bar()
>> yourpackage.sub_package.more_modules.foo()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With