python - 使用装饰器向 __all__ 添加名称是一种好习惯吗?

标签 python coding-style

这是 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/

相关文章:

python - 我在哪里可以找到 PEP 257 Docstring 约定的正确示例?

python - 如何将二元组列表转换为其第一个元素的列表

c# - 在方法中放置局部变量声明的最佳实践?

f# - F# 中全局变量的样式指南

python - 如何将函数列表组合成可调用对象

python - 使用scrapy创建一个简单的python爬虫

将文本文件读入 if 语句的 Python 解决方案

c++ - C 中的变量声明 typedefs 约定

python - 自定义 matplotlib 图 : chess board like table with colored cells

python - 如何为异步生成器提供来自 python.net 的事件