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 · 7 天前 · 1035 次点击

    另外

    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
    Hopetree
        1
    Hopetree  
       7 天前
    这样的吧
    if message.author:
    new_message['guildId'] = message.author
    hefish
        2
    hefish  
       7 天前
    这个,多写几句不费墨水吧。
    drymonfidelia
        3
    drymonfidelia  
    OP
       7 天前
    @Hopetree 这样更不简洁了
    jfcherng
        4
    jfcherng  
       7 天前   ❤️ 1
    是可以, 但不利於靜態分析
    getattr(message.guild, 'id', None)
    Dece
        5
    Dece  
       7 天前
    pydantic 可以看下这个,BaseModel 类有个方法 [.dict] , 支持传参数 exclude_none=True, 可以将类转为 dict ,并且忽略掉 None 值
    renmu
        6
    renmu  
       7 天前 via Android
    改用 defaultdict ,应该也许可以
    cdwyd
        7
    cdwyd  
       7 天前
    message.get('guild',{}).get('id', None)
    CrossMythic
        8
    CrossMythic  
       7 天前
    **({'authorId': message.author.id} if message.author else {})
    应该是可以,不过没啥意义
    customsshen
        9
    customsshen  
       7 天前
    message.guild.get("id")
    drymonfidelia
        10
    drymonfidelia  
    OP
       7 天前
    @customsshen AttributeError: 'NoneType' object has no attribute 'get'
    deplives
        12
    deplives  
       7 天前
    [None, message.guild.id][message.guild]
    lolizeppelin
        13
    lolizeppelin  
       7 天前
    别搞语法了,到时候搞得和 c#一样 getter setter 五种以上写法
    XueXianqi
        14
    XueXianqi  
       6 天前
    @deplives 你这个方法不行,列表的第二个元素拿不到会直接报错(因为此时没有判断 message.guild 就直接去取 message.guild 的 id 属性)
    XueXianqi
        15
    XueXianqi  
       6 天前
    直接用反射即可:"guildId": getattr(message.guild, "id", None)
    sampeng
        16
    sampeng  
       6 天前
    所以说 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  
       6 天前
    @sampeng 在大多语言里就是 ?? 操作符的事( python 后面也加上去了),你给我看 300 字小文章?
    Sawyerhou
        18
    Sawyerhou  
       6 天前
    楼上朋友们的解法非常聪明。

    不过真的比直接写好吗?会不会不太美观?
    还是说只是作为理论探讨,不应该于实际生产?
    marcong95
        19
    marcong95  
       6 天前
    @lisxour PEP 505 – None-aware operators 已经 deferred 了,你用的什么未来版本 Python ?
    abersheeran
        20
    abersheeran  
       6 天前
    @marcong95 #19
    @lisxour #17

    他大概用的是 https://mingshe.aber.sh/syntax/nullish-coalescing/ 😜怎么不算 Python 呢?
    marcong95
        21
    marcong95  
       6 天前
    @abersheeran 这语言的名字不禁令我想套一个公式~~

    Pythonista 是这样的。MíngShér 只要全身心投入到敲码就可以,可是 Pythonista 要考虑的事情就很多了。(手动狗头
    GPTBase
        22
    GPTBase  
       6 天前
    guild_id = getattr(message.guild, 'id', None),使用 getattr 函數:
    getattr 函數可以用來直接從對象中獲取屬性,如果該屬性不存在則返回預設值。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5019 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 09:16 · PVG 17:16 · LAX 02:16 · JFK 05:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.