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
XIVN1987
V2EX  ›  Python

PEP 802 – Display Syntax for the Empty Set

  •  
  •   XIVN1987 · 26 天前 · 1329 次点击
    >>> type({/})
    <class 'set'>
    >>> {/} == set()
    True
    

    感觉好奇怪的语法,,为啥非要引入一个空 set 语法??有啥特别大的好处吗?? set() 也挺短的啊??

    11 条回复    2025-08-10 15:06:05 +08:00
    iorilu
        1
    iorilu  
       26 天前
    就是感觉空 set 缺一个字面量写法呗, 别的都有, 唯独这个没

    想起来了, 空 tuple, 也没, 要不弄个(/)
    XIVN1987
        2
    XIVN1987  
    OP
       26 天前   ❤️ 1
    @iorilu

    In [14]: type(())
    Out[14]: tuple

    In [15]: () == tuple()
    Out[15]: True
    XIVN1987
        3
    XIVN1987  
    OP
       26 天前
    这个 {/} 大概是 python 首创语法了吧
    Vegetable
        4
    Vegetable  
       26 天前   ❤️ 1
    你是用多了不觉得奇怪吧

    pep 开头已经说的很清楚了,我认为理由很充分。

    > This complements the existing notation for empty tuples, lists, and dictionaries, which use (), [], and {} respectively.


    { i for i in range(10) }是 set
    { i: i for i in range(10) }是 dict

    你习惯了觉得正常,反正我一直认为 set 和 dict 的符号设计缺乏一致性,打个补丁虽然解决不了,但是能好一些。
    XIVN1987
        5
    XIVN1987  
    OP
       26 天前   ❤️ 1
    @Vegetable

    空 set 用 {},空 dict 用 {:} 最符合直觉,,但空 dict 已经用了 {},,为了兼容性不可能用这个方案。。

    既然符合直觉的方案已经没了,,那就没必要硬凑一个不符合直觉的方案来用,,毕竟 set() 本身也挺短的。。
    iorilu
        6
    iorilu  
       26 天前
    @XIVN1987 确实 ,tuple 比较特别, 空 tuple 可以()
    但有一个元素又不行了(1)

    但 set, 没有空 set, 但 1 个的没问题{1}

    唉, 还是不一致
    keakon
        7
    keakon  
       26 天前
    其实这样也行:
    >>> {*()}
    set()
    carlojie
        8
    carlojie  
       26 天前
    这他吗有意义吗? 都 ai 时代了
    ershierdu
        9
    ershierdu  
       25 天前 via Android
    踩过这个坑好多次了,经常以为{}是空集合
    iorilu
        10
    iorilu  
       25 天前
    @keakon
    >>> {*{}}
    set()
    fushall
        11
    fushall  
       25 天前
    @keakon 竟然还能这样啊,学到了哈哈哈
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5352 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 07:54 · PVG 15:54 · LAX 00:54 · JFK 03:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.