V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2021-02-04 10:18:37 +08:00 · 1762 次点击
    这是一个创建于 1149 天前的主题,其中的信息可能已经有所发展或是发生改变。

    目前在用 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 条回复    2021-02-04 10:57:12 +08:00
    karatsuba
        1
    karatsuba  
       2021-02-04 10:33:45 +08:00
    不知道,不用 toml
    crclz
        2
    crclz  
       2021-02-04 10:57:12 +08:00   ❤️ 2
    都可以。像 JAVA C#这种的,用 ENUM 是标准操作。所以 python 用 enum 算不上过度封装。

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

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

    当然,这是有依据的,例如 numpy 的 padding='zero'之类的传参,大家都没怎么抱怨这种设计。如果参数不知道填什么,大家都知道去看函数注释。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2832 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:14 · PVG 21:14 · LAX 06:14 · JFK 09:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.