[issue26632] __all__ decorator
Eryk Sun
report at bugs.python.org
Thu Mar 24 22:12:46 EDT 2016
Eryk Sun added the comment:
> work off its __name__ and __module__
Why is __module__ required? It seems to me this should only operate on the current module.
I added a prototype to Python/bltinmodule.c that gets or creates the __all__ list from the current globals (i.e. PyEval_GetGlobals). It accepts at most one positional argument and any number of keyword arguments. It adds the positional argument's __name__ to __all__, sets it in globals, and returns a reference for use as a decorator. The keyword argument dict is used to update globals and extend __all__.
Python 3.6.0a0 (default:3eec7bcc14a4+, Mar 24 2016, 20:40:52)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more
information.
>>> @public
... def foo():
... pass
...
>>> def bar(): pass
...
>>> public(bar, spam=1, eggs=2)
<function bar at 0x7efe96ca1048>
>>> __all__
['foo', 'spam', 'eggs', 'bar']
>>> foo, bar
(<function foo at 0x7efe96c8af28>, <function bar at 0x7efe96ca1048>)
>>> spam, eggs
(1, 2)
Maybe it should be generalized to handle multiple positional arguments. Currently it's an error:
>>> public(foo, bar)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: public expected at most 1 arguments, got 2
The positional argument must have a __name__ that's a string:
>>> public('CONST')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__name__'
>>> class C:
... __name__ = 1
...
>>> public(C())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __name__ must be a string
If it's used to decorate a method definition, it stores a reference to the function in the module's globals. That's not very useful, but at least it won't lead to an error with a star import.
----------
nosy: +eryksun
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26632>
_______________________________________
More information about the Python-bugs-list
mailing list