Quick Python: Export Decorator

Brandon Rozek

June 14, 2020

A great StackOverflow post by Aaron Hall that shows how you can create an export decorator in order to not have to specify all the names you want to expose via __all__.

The Decorator:

import sys

def export(fn):
    mod = sys.modules[fn.__module__]
    if hasattr(mod, '__all__'):
        mod.__all__.append(fn.__name__)
    else:
        mod.__all__ = [fn.__name__]
    return fn

Usage:

__all__ = []

@export # otherwise __all__ = ['test']
def test():
    print("test")