使用装饰器将名称添加到__all__是一个好习惯吗? [英] Is it a good practice to add names to __all__ using a decorator?
本文介绍了使用装饰器将名称添加到__all__是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是Python中的良好做法(来自活动状态食谱 - Public Decorator )?
Is this a good practice in Python (from 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 __
The general idea would be to define a decorator that takes a function or class
and adds its name to the __all__
of the current module.
推荐答案
是的,这是一个很好的做法。这个装饰器允许你在函数或类定义时声明你的意图,而不是直接在之后。这使你的代码更加可读。
Yes, it's a good practice. This decorator allows you to state your intentions right at function or class definition, rather than directly afterwards. That makes your code more readable.
@public
def foo():
pass
@public
class bar():
pass
class helper(): # not part of the modules public interface!
pass
注意:
模块的用户仍然可以通过
。它只是没有从 modulename.helper
访问从modulename import *
导入。
这篇关于使用装饰器将名称添加到__all__是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文