When is __all__ used while importing a module in Python?

Viewed 62

Say there is a greetings module like this:

__all__ = []

def offer(func):
   __all__.append(func.__name__)
   return func

@offer
def spanish():
   return "Hola!"

@offer
def japanese():
   return "Konnichiwa"

When does the interpreter decide what to import when from greetings import * is run?

2 Answers

When does the interpreter decide what to import when from greetings import * is run?

When you say from greetings import *, interpreter loads and executes the greeting module, then it references the objects mentioned in the __all__ list back into the current module's global namespace so that you can access them using those symbols inside the __all__.

I think you guessed because you defined __all__ at the beginning of the module and it's empty, nothing is going to be imported. No that's not the case.

__all__ tells a list of module names that should be imported when from package import * is encountered.

For Example, If __all__ is not defined, the statement from greetings.languages import * does not import all submodules from the package greetings.languages into the current namespace; it only ensures that the package greetings.languages has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package.

Related