Python 中的安全解除引用

Safe dereferencing in Python(Python 中的安全解除引用)

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

问题描述

Groovy 有一个很好的操作符用于安全解除引用,这有助于避免 NullPointerExceptions:

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

variable?.method()

method 只会被调用,如果 variable 不是 null.

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()?

推荐答案

EDIT 2021:

有一个新的包,它是一种在 Python 中完全具有此功能的黑客.这是存储库:https://github.com/paaksing/nullsafe-python>

There is a new package that is sort of a hack featuring exactly this functionality in Python. Here is the repo: https://github.com/paaksing/nullsafe-python

from nullsafe import undefined, _

value = _(variable).method()
assert value is undefined
assert not value
assert value == None

适用于 AttributeErrorKeyError 以及

dic = {}
assert _(dic)["nah"] is undefined
assert _(dic).nah is undefined

包装的对象类型将保持有效.

The wrapped object typings will remain effective.

  1. 不,没有.

  1. No, there isn't.

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

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 有时用于表示没有值.但不知何故 - 也许是因为惯用代码返回 null 对象,其中合理或抛出异常以指示严重失败 -我每月只收到两次 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 中的安全解除引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Python 中的安全解除引用

基础教程推荐