推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Contextualist
V2EX  ›  Python

Python 类型注解, Enum 还是 str Literal?

  •  
  •   Contextualist ·
    Contextualist · Feb 4, 2021 · 2898 views
    This topic created in 2060 days ago, the information mentioned may be changed or developed.

    目前在用 attrs 做 TOML 配置的结构定义。遇到有些条目是联合类型,可以指定关键字也可以给具体数值,比如以下 TOML:

    attr0 = 0.98
    # 或者
    #attr0 = "magicx"
    

    那么这个条目的定义有两种写法,用 str Literal:

    import attr
    from typing import Union, Literal
    
    @attr.s(auto_attribs=True)
    class Config:
        attr0: Union[float, Literal["magicx"]]
    
    ...
    config = parse_config()
    if config.attr0 == "magicx":
        ...
    

    或者用 Enum:

    import attr
    from typing import Union
    from enum import Enum
    
    class Attr0KW(Enum):
        MAGICX = "magicx"
    
    @attr.s(auto_attribs=True)
    class Config:
        attr0: Union[float, Attr0KW]
    
    ...
    config = parse_config()
    if config.attr0 is Attr0KW.MAGICX:
        ...
    

    像这种只有一个关键字的,写个 Enum 又觉得过度封装了,但用 str Literal 又觉得不严谨。应该如何取舍?

    2 replies  •  2021-02-04 10:57:12 +08:00
    karatsuba
        1
    karatsuba  
       Feb 4, 2021
    不知道,不用 toml
    crclz
        2
    crclz  
       Feb 4, 2021   ❤️ 2
    都可以。像 JAVA C#这种的,用 ENUM 是标准操作。所以 python 用 enum 算不上过度封装。

    如果使用你这个类的开发者很多,那么就尽量使用 Enum 。如果自己用,就使用字符串。

    我个人的建议是,其实 python 作为一门动态语言,也该有动态语言的样子,就直接使用字符串就行了,约束什么的也没有必要用类型注解来做,影响开发速度。

    当然,这是有依据的,例如 numpy 的 padding='zero'之类的传参,大家都没怎么抱怨这种设计。如果参数不知道填什么,大家都知道去看函数注释。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   950 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 18:45 · PVG 02:45 · LAX 11:45 · JFK 14:45
    ♥ Do have faith in what you're doing.