如何将文档字符串放在枚举上? [英] How do I put docstrings on Enums?

查看:18
本文介绍了如何将文档字符串放在枚举上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.4 有一个新的 enum 模块和 Enum 数据类型.如果您还无法切换到 3.4,Enum 已被反向移植.

由于 Enum 成员支持文档字符串,就像几乎所有 python 对象一样,我想设置它们.有没有简单的方法来做到这一点?

解决方案

是的,它是迄今为止我最喜欢的食谱.作为奖励,您也不必指定整数值.举个例子:

class AddressSegment(AutoEnum):misc = "当前未跟踪"序数 = "N S E W NE NW SE SW"次要 =apt 楼楼等"street = "st ave blvd etc"

你可能会问为什么我不只是让 "N S E W NE NW SE SW" 作为 ordinal 的值?因为当我看到 <AddressSegment.ordinal: 'NSEW NE NW SE SW'> 得到它的代表时会有点笨拙,但在文档字符串中随时提供这些信息是一个很好的妥协.>

这是 Enum 的配方:

class AutoEnum(enum.Enum):"""从 1 开始自动编号枚举成员.包括对每个成员的自定义文档字符串的支持."""#def __new__(cls, *args):"""忽略参数(将在 __init__ 中处理."""值 = len(cls) + 1obj = object.__new__(cls)obj._value_ = 值返回对象#def __init__(self, *args):"""可以处理 0 或 1 个参数;更多需要自定义 __init__.0 = 没有文档字符串的自动编号1 = 带有文档字符串的自动编号2+ = 需要自定义 __init__"""如果 len(args) == 1 和 isinstance(args[0], (str, unicode)):self.__doc__ = args[0]elif 参数:raise TypeError('%s 未处理 -- 需要自定义 __init__' % (args,))

并在使用中:

<预><代码>>>>列表(地址段)[<AddressSegment.ordinal: 1>, <AddressSegment.secondary: 2>, <AddressSegment.misc: 3>, <AddressSegment.street: 4>]>>>地址段.secondary<AddressSegment.secondary: 2>>>>AddressSegment.secondary.__doc__'apt bldg 地板等'

我在 __init__ 中而不是在 __new__ 中处理参数的原因是为了让子类化 AutoEnum 更容易,如果我想进一步扩展它.

Python 3.4 has a new enum module and Enum data type. If you are unable to switch to 3.4 yet, Enum has been backported.

Since Enum members support docstrings, as pretty much all python objects do, I would like to set them. Is there an easy way to do that?

解决方案

Yes there is, and it's my favorite recipe so far. As a bonus, one does not have to specify the integer value either. Here's an example:

class AddressSegment(AutoEnum):
    misc = "not currently tracked"
    ordinal = "N S E W NE NW SE SW"
    secondary = "apt bldg floor etc"
    street = "st ave blvd etc"

You might ask why I don't just have "N S E W NE NW SE SW" be the value of ordinal? Because when I get its repr seeing <AddressSegment.ordinal: 'N S E W NE NW SE SW'> gets a bit clunky, but having that information readily available in the docstring is a good compromise.

Here's the recipe for the Enum:

class AutoEnum(enum.Enum):
    """
    Automatically numbers enum members starting from 1.

    Includes support for a custom docstring per member.
    """
    #
    def __new__(cls, *args):
        """Ignores arguments (will be handled in __init__."""
        value = len(cls) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj
    #
    def __init__(self, *args):
        """Can handle 0 or 1 argument; more requires a custom __init__.

        0  = auto-number w/o docstring
        1  = auto-number w/ docstring
        2+ = needs custom __init__

        """
        if len(args) == 1 and isinstance(args[0], (str, unicode)):
            self.__doc__ = args[0]
        elif args:
            raise TypeError('%s not dealt with -- need custom __init__' % (args,))

And in use:

>>> list(AddressSegment)
[<AddressSegment.ordinal: 1>, <AddressSegment.secondary: 2>, <AddressSegment.misc: 3>, <AddressSegment.street: 4>]

>>> AddressSegment.secondary
<AddressSegment.secondary: 2>

>>> AddressSegment.secondary.__doc__
'apt bldg floor etc'

The reason I handle the arguments in __init__ instead of in __new__ is to make subclassing AutoEnum easier should I want to extend it further.

这篇关于如何将文档字符串放在枚举上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆