c3cris c3cris - 4 months ago 22
Python Question

How to import the full package

This is my app structure using python 3.5

app
__init__.py # running the code from here
module
__init__.py
test.py # want access to this
^-- test_function() is here
test2.py # and this one too


I am full aware I can access test with the following. note I am running this using the following cmd
python 3 /app/__init__.py
need access to
/app/module/test.py


from module import test
test.test_function()
# works


I can also import it into global scope (bad practice)

from module.test import test_function
# works


And I know i can also use

import module.test
# works


But what I would like to do is import the full module (or package sorry for my terminology)

I want to import the full package, example:

import module

module.test.test_function()


But I seem to get

AttributeError: module 'module' has no attribute 'test'


bonus question
If importing the full package is not a good practice then I don't mind being explicit and using
from module import test
, please let me know.

PS I have tried adding imports in /app/module/__init__.py because it gets called during the import, but it seems that it doesn't work

I added
import test
in
/app/module/__init__.py
but when I try it test seems empty.

import module # module now has import test in its __init__
print(dir(module.test))
# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']


As you can see it's missing test_function()

Answer

Few additional thoughts to Loading all modules in a folder in Python

$ tree
.
├── mod
│   ├── __init__.py
│   ├── test.py
└── run.py

__init__.py

# to import all objects use star '*' instead of name literals
from test import hello_world

test.py

def hello_world():
    print('Hello World!')

run.py

import mod

if __name__ == '__main__':
    mod.hello_world()

Result

$ python run.py 
Hello World!

You can import any modules, sub modules or anything else to make it part of "public" interface of package.

UPD: I'm highly recomend you to read packages topic from documentation. As it sad

It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a __path__ attribute is considered a package.

You can think in this way: when you importing module, you are loading all objects from module_name.py file, but when you importing package you are loading __init__.py file.

Packages usually contain so called public interface, which contains only reusable components related to this package without helper functions, etc. In this way packages hides some code from outer scope (where it will be used) while importing.

Comments