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

Nick Coghlan ncoghlan at gmail.com
Fri May 9 13:58:51 CEST 2014


On 9 May 2014 18:53, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, May 9, 2014 at 6:45 PM, Peter Otten <__peter__ at web.de> wrote:
>> I'm mostly posting to suggest an alternative implementation for your
>> personal use ;)
>>
>> def export(f):
>>     sys._getframe(1).f_globals.setdefault("__all__", []).append(f.__name__)
>>     return f
>
> sys._getframe, in my opinion, isn't so much code "smell" as
> "Mythbusters' 1987 Chevrolet"... :)

As this subthread suggests, the main problem with the concept of
decorator based public/private markings is "If the implementation is
hard to explain, it's a bad idea." You essentially have to use some
form of dynamic scoping in order to modify __all__ in the right
module, and then that limits your ability to wrap the export decorator
inside other helper functions.

In many cases, the fact that underscore prefixed names are excluded
from the implicit all is sufficient to avoid the need to worry too
much about defining an explicit __all__ attribute. Problems typically
only arise due to imported modules being implicitly re-exported.

If folks really want to avoid defining an explicit __all__, then it
isn't that hard to define a helper function that allows a module to be
finished with a line like:

    __all__ = all_without_modules(globals())

It generally isn't worth the hassle, though, especially when star
imports are strongly discouraged in the first place.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list