您是否可以构建一个与以下Python 2.7 grammar rules匹配的最小有效源代码示例?是否可以不产生运行时错误?
(1) atom: '[' [listmaker] ']'
(2) listmaker: test list_for
(3) list_for: 'for' exprlist 'in' testlist_safe
(4) testlist_safe: old_test
(5) old_test: old_lambdef
(6) old_lambdef: 'lambda' [varargslist] ':' old_test
到目前为止我能达到的最好结果是:
L = [ fn() for fn in (lambda: x for x in xrange(3)) ]
但我的解决方案的问题是围绕" lambda"的括号。你能不用括号建立一个例子吗?如果没有,那你怎么解释为什么你不能在lambda'即使它完全符合语法规则?
答案 0 :(得分:5)
[x for x in lambda: 1]
这很简单。当然,这会在运行时产生TypeError,但语法不是为了排除会产生TypeErrors的构造。
没有办法在运行时没有异常,因为old_lambdef
总是求值为一个不可迭代的函数对象。 old_lambdef
的结构中没有任何地方可以插入一些东西来让Python调用函数; Python将尝试迭代函数对象本身,而不是调用它并迭代返回值。
testlist_safe
和old_test
定义的完整形式为
testlist_safe: old_test [(',' old_test)+ [',']]
old_test: or_test | old_lambdef
testlist_safe
并非总是单old_test
,old_test
也不总是old_lambdef
。允许testlist_safe
为old_test
,old_test
允许old_lambdef
为grid-container {
display: grid; /* 1 */
grid-auto-rows: 50px; /* 2 */
grid-gap: 10px; /* 3 */
grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); /* 4 */
}
[short] {
grid-row: span 1; /* 5 */
background-color: green;
}
[tall] {
grid-row: span 2;
background-color: crimson;
}
[taller] {
grid-row: span 3;
background-color: blue;
}
[tallest] {
grid-row: span 4;
background-color: gray;
}
。一起做这些事情总是在运行时产生异常,但它们不会使语法复杂化只是为了阻止人们一起做这些事情。