[New-bugs-announce] [issue26632] __all__ decorator

Barry A. Warsaw report at bugs.python.org
Wed Mar 23 22:33:17 EDT 2016


New submission from Barry A. Warsaw:

This is probably terrible, but given how difficult it is to keep __all__'s up to date, maybe something like this can be useful.  I literally whipped this up in about 5 minutes, so sit back and watch the bikeshedding!

import sys

def public(thing):
    if isinstance(thing, str):
        mdict = sys._getframe(1).f_globals
        name = thing
    else:
        mdict = sys.modules[thing.__module__].__dict__
        name = thing.__name__
    dunder_all = mdict.setdefault('__all__', [])
    dunder_all.append(name)
    return thing


Then:

@public
def baz(a, b):
    return a + b

@public
def buz(c, d):
    return c / d

def qux(e, f):
    return e * f

class zup:
    pass

@public
class zap:
    pass

public('CONST1')
CONST1 = 3

CONST2 = 4

public('CONST3')
CONST3 = 5

Normally for any callable with an __name__, you can just decorate it with @public to add it to __all__.  Of course that doesn't worth with things like constants, thus the str argument.  But of course that also requires sys._getframe() so blech.

----------
messages: 262319
nosy: barry
priority: normal
severity: normal
status: open
title: __all__ decorator
versions: Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26632>
_______________________________________


More information about the New-bugs-announce mailing list