As everything in Python is an object, and all objects can be assigned to variables, one cannot create a non-erroring value that cannot be assigned to a variable.
However, as an aside, there exist expressions that can never be assigned to a variable. One would think expressions that throw errors fall within this box, such as 1/0, which throws ZeroDivisionError:
>>> foo=1/0
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
foo=1/0
ZeroDivisionError: division by zero
but in fact those expressions can be caught within try/except statements, such as the one below:
try:
foo=1/0
except:
pass
This is not the end of the story however, since there exist expressions which cause the Python interpreter to segfault. The shortest one that I'm aware of is from Codegolf Stack Exchange:
exec((lambda:0).__code__.replace(co_consts=()))
Which will always crash the python interpreter, even within a try-except statement.
发布评论
评论(1)
由于Python中的一切都是对象,并且所有对象都可以分配给变量,因此无法创建不能分配给变量的无错误值。
然而,顺便说一句,存在永远不能分配给变量的表达式。人们可能会认为抛出错误的表达式属于此框,例如
1/0
,它会抛出 ZeroDivisionError:实际上这些表达式可以在 try/ except 语句中捕获,例如下面的:
但 然而,故事还没有结束,因为存在导致 Python 解释器出现段错误的表达式。我所知道的最短的一个来自 Codegolf Stack Exchange:
即使在 try- except 语句中,它也总是会导致 python 解释器崩溃。
As everything in Python is an object, and all objects can be assigned to variables, one cannot create a non-erroring value that cannot be assigned to a variable.
However, as an aside, there exist expressions that can never be assigned to a variable. One would think expressions that throw errors fall within this box, such as
1/0
, which throws ZeroDivisionError:but in fact those expressions can be caught within try/except statements, such as the one below:
This is not the end of the story however, since there exist expressions which cause the Python interpreter to segfault. The shortest one that I'm aware of is from Codegolf Stack Exchange:
Which will always crash the python interpreter, even within a try-except statement.