__all__ in Python and What It Does

Let’s say we have 2 Python scripts.

  • main.py — the script that we want to run
  • helper.py — main.py imports stuff from this script
  • these 2 scripts are in the same folder
# helper.py
a = 4
b = 5
c = 6

def test():
  print('test')
# main.py
from helper import *

print(a, b, c)    # 4 5 6
test()            # test
  • In main.py, the line from helper import * means that everything inside helper.py is imported into main.py
  • this is why we can use a b c and test in main.py

What if I want to do a partial import?

Let’s say instead of import a b c and test, I only wish to import a and b only. In main.py, we can change up the from helper import * statement.

# helper.py
a = 4
b = 5
c = 6

def test():
  print('test')
# main.py
from helper import a, b

print(a, b)      # 4 5

# attempting to use c or test will cause error
  • the statement from helper import a, b imports ONLY a and b from helper.py — c and test are not imported.
  • this is how we can partial import

Click Here 

Tags: Python Scripts