递延评估python [英] Deferred evaluation in python
问题描述
我听说过python中的延迟评估(例如此处),是指仅在使用lambda时,解释器如何评估它们?还是这是描述python的动态设计如何在运行时之前不会捕获很多错误的合适术语?
I have heard of deferred evaluation in python (for example here), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many errors until runtime?
还是我完全错过了什么?
Or am I missing something entirely?
推荐答案
Dietrich的答案很不错,但我只想补充一下,最简单的延期评估形式是if
语句:
Dietrich's answer is a good one, but I just want to add that the simplest form of deferred evaluation is the if
statement:
if True:
x = 5
else:
x = y # huh? what is y?
尽管else
子句没有意义-y
是未定义的,但是此代码可以解析并正确运行. else
子句仅被解析-因此它在语法上应该是有效的Python.这实际上可以用于一些简单的代码:
This code parses and runs correctly, although the else
clause makes no sense - y
is undefined. The else
clause is only being parsed - so it should be valid Python syntactically. This can be actually used for some simple code:
if stuff:
print stuff.contents
else:
print "no stuff"
在强类型语言中,这是行不通的,因为键入stuff.contents
要求stuff
为具有contents
属性的特定类型.在Python中,由于if
中的语句的求值延迟,因此不一定是正确的. stuff
可以是显然没有属性的None
,并且解释器将仅使用else
子句而无需执行第一个子句.因此,这是有效的Python,甚至是一个惯用法,使代码更简单.
In a strongly typed language this wouldn't work, because to type stuff.contents
requires stuff
to be of a certain type that has a contents
attribute. In Python, because of the deferred evaluation of the statements in if
, this isn't necessarily true. stuff
can be None
which obviously has no attributes, and the interpreter will just take the else
clause without executing the first. Hence this is valid Python and even an idiom, that makes code simpler.
这篇关于递延评估python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!