Feb 22, 2019

__all__ in Python

__all__ in a module

e.g. module.py:

__all__ = ['foo', 'Bar']
means that when you import * from the module, only those names in the __all__ are imported:

from module import *   
# imports only foo and Bar (through wild card)

test1.py

__all__ = ['var1', 'func1']

var1 = 100

def func1():
    return 'func1'

def func2():
    return 'func2'


test2.py
from test import var1, func1, func2
print var1
print func1()
print func2()

Output:
100
func1
func2


test3.py
from test import *

print var1
print func1()
print func2() #NameError: name 'func2' is not defined

Output:
100
func1
NameError: name 'func2' is not defined


No comments:

Post a Comment