4

I trying to understand how to manage module with __all. For example, I have following structured code:

main.py |=> /database |=> __init__.py |=> engine (with variables engine, session, etc.) 

now I want to be able to import session and engine instances directly from database module like:

from database import session 

I tried to add line __all__ = ['session'] or __all__ = ['engine.session'] to __init__py but when I trying to do import I've got an exception AttributeError: 'modile' object has not attribute 'engine.session'.

Is there any way to achieve wanted behavior?

1 Answer 1

5

Listing names in __all__ does not, by itself, import items into a module. All it does is list names to import from that module if you used from database import * syntax.

Import session into database/__init__.py:

from .engine import session 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for solution, but I still have a question - if I importting all required classes/functions/variables in __init__.py I can do not bother about filling __all__ - all I imported already available. So, what which reasons to use __all__?
@AlexG.P.: use __all__ to flag what names are 'importable'; if someone does from database import * only names listed in __all__ will be imported, rather than all names in the namespace of the module.
Ahh, it only can descrease ramges of imported types, but not increase it. Great thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.