Python 中 message.guild.id if message.guild else None 这种表达式,还能写得更简洁吗? - V2EX
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
drymonfidelia
V2EX    Python

Python 中 message.guild.id if message.guild else None 这种表达式,还能写得更简洁吗?

  •  
  •   drymonfidelia 2024-06-20 10:38:14 +08:00 2083 次点击
    这是一个创建于 483 天前的主题,其中的信息可能已经有所发展或是发生改变。

    另外

    new_message = { 'messageId': message.id, 'authorId': message.author.id, 'content': message.content, 'guildId': message.guild.id if message.guild else None } 

    如果我想让 authorId 在 message.author 为 None 时直接没有这项,有办法在定义这个 dict 就实现,而不是创建完再 del 或者创建完再加上吗?

    22 条回复    2024-06-21 14:23:36 +08:00
    td width="auto" valign="top" align="left">
        1
    Hopetree  
       2024-06-20 10:50:46 +08:00
    这样的吧
    if message.author:
    new_message['guildId'] = message.author
    Hopetree
    hefish
        2
    hefish  
       2024-06-20 10:52:44 +08:00
    这个,多写几句不费墨水吧。
    drymonfidelia
        3
    drymonfidelia  
    OP
       2024-06-20 10:52:50 +08:00
    @Hopetree 这样更不简洁了
    jfcherng
        4
    jfcherng  
       2024-06-20 10:54:18 +08:00   1
    是可以, 但不利於分析
    getattr(message.guild, 'id', None)
    Dece
        5
    Dece  
       2024-06-20 10:55:15 +08:00
    pydantic 可以看下这个,BaseModel 类有个方法 [.dict] , 支持传参数 exclude_nOne=True, 可以将类转为 dict ,并且忽略掉 None 值
    renmu
        6
    renmu  
       2024-06-20 10:57:33 +08:00 via Android
    改用 defaultdict ,应该也许可以
    cdwyd
        7
    cdwyd  
       2024-06-20 11:05:11 +08:00
    message.get('guild',{}).get('id', None)
    CrossMythic
        8
    CrossMythic  
       2024-06-20 11:15:55 +08:00
    **({'authorId': message.author.id} if message.auhor else {})
    应该是可以,不过没啥意义
    customsshen
        9
    customsshen  
       2024-06-20 11:23:30 +08:00
    message.guild.get("id")
    drymonfidelia
        10
    drymonfidelia  
    OP
       2024-06-20 11:26:55 +08:00
    @customsshen AttributeError: 'NoneType' object has no attribute 'get'
    qq135449773
        11
    qq135449773  
       2024-06-20 11:44:52 +08:00
    deplives
        12
    deplives  
       2024-06-20 12:51:38 +08:00
    [None, message.guild.id][message.guild]
    lolizeppelin
        13
    lolizeppelin  
       2024-06-20 15:32:46 +08:00
    别搞语法了,到时候搞得和 c#一样 getter setter 五种以上写法
    XueXianqi
        14
    XueXianqi  
       2024-06-20 19:11:39 +08:00
    @deplives 你这个方法不行,列表的第二个元素拿不到会直接报错(因为此时没有判断 message.guild 就直接去取 message.guild 的 id 属性)
    XueXianqi
        15
    XueXianqi  
       2024-06-20 19:13:30 +08:00
    直接用反射即可:"guildId": getattr(message.guild, "id", None)
    sampeng
        16
    sampeng  
       2024-06-20 19:39:51 +08:00
    所以说 xxx 是 python/js 的生产力。


    1. 在 Python 中,如果你想简化表达式 message.guild.id if message.guild else None ,可以使用内置的 getattr() 函数,这种方式可以更加简洁且直观。

    使用 getattr() 函数,你可以直接指定想要获取的属性,如果该属性不存在,则返回你指定的默认值。这里是如何用 getattr() 来重写你的表达式:

    getattr(message.guild, 'id', None)

    这行代码尝试从 message.guild 获取 id 属性,如果 message.guild 是 None 或者 message.guild 没有 id 属性,它会返回 None 。这种方式可以使代码更加简洁且易于理解。

    2.可以在定义字典时使用条件表达式( ternary operator ),这样就可以在初始化时直接决定是否包含某个键。这里是一个针对你需求的示例代码:
    new_message = {
    'messageId': message.id,
    'content': message.content,
    'guildId': message.guild.id if message.guild else None,
    **({'authorId': message.author.id} if message.author else {})
    }
    在这个示例中,我使用了字典解包(**)来根据条件动态地添加 authorId 键。如果 message.author 是 None ,那么这部分字典将不会被添加到 new_message 中。这样一来,new_message 就只会在 message.author 不为 None 时包含 authorId 。这种方法避免了创建后修改字典的需求,使得代码更加简洁和高效。
    lisxour
        17
    lisxour  
       2024-06-21 09:07:57 +08:00
    @sampeng 在大多语言里就是 ?? 操作符的事( python 后面也加上去了),你给我看 300 字小文章?
    Sawyerhou
        18
    Sawyerhou  
       2024-06-21 09:28:18 +08:00
    楼上朋友们的解法非常聪明。

    不过真的比直接写好吗?会不会不太美观?
    还是说只是作为理论探讨,不应该于实际生产?
    marcong95
        19
    marcong95  
       2024-06-21 09:57:45 +08:00
    @lisxour PEP 505 None-aware operators 已经 deferred 了,你用的什么未来版本 Python ?
    abersheeran
        20
    abersheeran  
       2024-06-21 11:19:50 +08:00
    @marcong95 #19
    @lisxour #17

    他大概用的是 https://mingshe.aber.sh/syntax/nullish-coalescing/ 怎么不算 Python 呢?
    marcong95
        21
    marcong95  
       2024-06-21 11:26:49 +08:00
    @abersheeran 这语言的名字不禁令我想套一个公式~~

    Pythonista 是这样的。MíngShér 只要全身心投入到敲码就可以,可是 Pythonista 要考虑的事情就很多了。(手动狗头
    GPTBase
        22
    GPTBase  
       2024-06-21 14:23:36 +08:00
    guild_id = getattr(message.guild, 'id', None),使用 getattr 函:
    getattr 函可以用直接象中取性,如果性不存在返回值。
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     1563 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 27ms UTC 16:22 PVG 00:22 LAX 09:22 JFK 12:22
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86