这是Python中的一个很好的练习(从Active State Recipes -- Public Decorator)?使用装饰器向__all__添加名称是一种好的做法吗?
import sys
def public(f):
"""Use a decorator to avoid retyping function/class names.
* Based on an idea by Duncan Booth:
http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a
* Improved via a suggestion by Dave Angel:
http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8a42e1
"""
all = sys.modules[f.__module__].__dict__.setdefault('__all__', [])
if f.__name__ not in all: # Prevent duplicates if run from an IDE.
all.append(f.__name__)
return f
public(public) # Emulate decorating ourself
总的想法是定义一个装饰,需要一个功能或 类,并增加了它的名字到当前模块的__all__
。
修正了标题,正如有些人指出的那样 – 2011-06-01 18:57:42
虽然这看起来不错,但我发现它混淆了我的IDE(PyCharm 2016.1.4),它大部分都会破坏目的。如果有足够的IDE支持,我会使用它。 – 2016-07-13 20:22:25
获得这个装饰器100%防弹似乎更难:看到[Python bug#26632](https://bugs.python.org/issue26632)和['atpublic'模块](https:// pypi。 python.org/pypi/atpublic)在那里提到。 – kostix 2016-12-10 09:25:29