[Python-ideas] Adding an "export" decorator in (e.g.) functools

Markus Unterwaditzer markus at unterwaditzer.net
Sat May 10 21:30:55 CEST 2014


On Fri, May 09, 2014 at 12:38:34AM -0500, Bill Winslow wrote:
> Hey guys.
> 
> This is simple pattern I've added to my own "myutils.py" file, which I
> think could see wide use if added to the standard library.
> 
> Simply, it's the following function meant to be used primarily as a
> decorator.
> 
>     def export(func):
>          global __all__
>          if callable(func) and hasattr(func, '__name__'):
>              try:
>                  __all__.append(func.__name__)
>              except NameError:
>                  __all__ = [func.__name__]
>         return func

Another version which doesn't have the bug mentioned by Chris, and works
without getframe:

    def export(f):
        module = __import__(f.__module__)
        if not hasattr(module, '__all__'):
            module.__all__ = []
        module.__all__.append(f.__name__)
        return f

-- Markus


More information about the Python-ideas mailing list