Python Forum

Full Version: module attributes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
instructions for the botocore module make reference to using botocore.session. when i do import botocore.session i can use botocore.session just fine. but if i just do import botocore there is no botocore.session defined. doing dir(botocore) shows there are other attributes defined, but session is not among them.

1. what is this feature of modules referred to or called?

2. why would i want to use this feature in a module i create?

3. how do i make my module work this way (in case it is not the default)?

4. how do i make my module not work this way (in case it is the default)?
It's the way they have build the package.
botocore is a folder that contain session.py and a blank __init__.py.
botocore/
 |-- __init__.py
 |-- session.py
# session.py
def egg():
    print('i am foo')
Usage:
λ ptpython
>>> import botocore

>>> botocore.session
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'botocore' has no attribute 'session'
module 'botocore' has no attribute 'session'

>>> # Have to use 
>>> import botocore.session

>>> botocore.session.egg()
i am foo
There is a fix for this bye modifying the blank import in __init__.py .
# __init__.py
from .session import egg
Usage:
λ ptpython
>>> import botocore

>>> botocore.session.egg()
i am foo

>>> # Now will also work without session,also we can call egg() function in session.py directly 
>>> botocore.egg()
i am foo
When build a package have to think of stuff like this.
The last version is for me much more user friendly.

Can of course have in doc that most use import botocore.session.bar.somthing,
i do not like import like this Dodgy
The way around this when build own package is to modify __init__.py(not all in the subfolders but one in main package folder) or also look at __all__ to severe stuff easier to users.