使用Python安全解引用 [英] Safe dereferencing in Python

查看:126
本文介绍了使用Python安全解引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy有一个很好的安全解引用运算符,有助于避免NullPointerExceptions:

Groovy has a nice operator for safe dereferencing, which helps to avoid NullPointerExceptions:

variable?.method()

仅当variable不是null时,才会调用method.

The method will only be called, if variable is not null.

有没有办法在Python中做同样的事情?还是我必须写if variable: variable.method()?

Is there a way to do the same in Python? Or do I have to write if variable: variable.method()?

推荐答案

  1. 不,没有.

  1. No, there isn't.

但是要检查None,您不写if x:,而是写if x is None:.这是一个重要的区别-对于许多可能完全正确的值,x的计算结果为False(最值得注意的是0等效数字和空集合),而x is None 的计算结果为True如果引用x指向单例对象None.

But to check for None, you don't write if x:, you write if x is None:. This is an important distinction - x evaluates to False for quite a few values that are propably perfectly valid (most notably 0-equivalent numbers and empty collections), whereas x is None only evaluates to True if the reference x points to the singleton object None.

从个人经验来看,很少需要这样的操作员.是的,有时None用来表示没有值.但是不知何故-也许是因为惯用代码返回了空对象,在此处明智或抛出异常以指示严重故障-我每月只能获得两次AttributeError: 'NoneType' object has no attribute '...'.

From personal experience, such an operator would be needed very rarely. Yes, None is sometimes used to indicate no value. But somehow - maybe because idiomatic code returns null objects where sensible or throws exceptions to indicate critical failure - I only get an AttributeError: 'NoneType' object has no attribute '...' twice a month.

我认为这可能是一个错误的功能. null有两个含义-忘记初始化"和没有数据".第一个是错误,应该引发异常.第二种情况通常比让我们不调用此方法"需要更多的复杂处理.当我向数据库/ORM请求UserProfile时,它不存在,而我得到了null ...我是否要无声地跳过该方法的其余部分?还是我真的想(当在库代码"中)抛出适当的异常(因此用户(代码)"知道用户不在那儿并且可以做出反应...或忽略它)或(当我在对特定功能进行编码)向用户显示一条明智的消息(该用户不存在,您无法将其添加到您的朋友列表中")?

I would argue that this might be a misfeature. null has two meanings - "forgot to initialize" and "no data". The first is an error and should throw an exception. The second case usually requires more elaborate handling than "let's just not call this method". When I ask the database/ORM for a UserProfile, it's not there and I get null instead... do I want to silently skip the rest of the method? Or do I really want to (when in "library code") throw an approriate exception (so "the user (code)" knows the user isn't there and can react... or ignore it) or (when I'm coding a specific feature) show a sensible message ("That user doesn't exist, you can't add it to your friend list") to the user?

这篇关于使用Python安全解引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆