Sobes.tech
Junior

How to import all content of a module in Python?

sobes.tech AI

Answer from AI

# Importing all contents of the module "my_module"
from my_module import *

# Now all names (variables, functions, classes) from my_module
# are directly accessible without specifying the module name.
# For example, if my_module has a function 'my_function',
# you can call it like:
# my_function()

Using from module import * imports all public names from the specified module directly into the current namespace. Public names are those that do not start with an underscore _. However, if the module defines a list __all__, then only the names listed in this list are imported.

Advantages:

  • Reduces code length, as there is no need to specify the module name when using its contents.

Disadvantages:

  • Can lead to name conflicts if the current namespace already contains variables or functions with the same names as those in the imported module.
  • Makes it harder to determine where a particular name came from, complicating debugging.
  • Is considered bad practice in PEP 8, especially for large modules, due to the uncertainty about what exactly is imported.

In most cases, it is preferable to use the regular import import module and access elements via module.name, or explicitly import only the names that are actually needed: from module import name1, name2.

Example with __all__:

If my_module.py contains the following:

# my_module.py
__all__ = ['my_function', 'my_variable']

def my_function():
    print("Hello")

my_variable = 10

def _internal_function():
    print("Internal")
# main.py
from my_module import *

my_function()  # Works
print(my_variable) # Works
# _internal_function() # Will raise NameError, as it is private and not in __all__