这是 Python 中的一个好习惯吗(来自 Active State Recipes -- Public Decorator)?
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__
中。
最佳答案
在 Python 中更惯用的方法是通过以下划线开头将私有(private)函数标记为私有(private):
def public(x):
...
def _private_helper(y):
...
更多的人会熟悉这种风格(语言也支持:_private_helper
即使你不使用 __all__
也不会被导出)而不是你的public
装饰器。
关于python - 使用装饰器向 __all__ 添加名称是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6206089/