SystemError when defining

Chris Angelico rosuav at gmail.com
Thu Nov 3 19:51:46 EDT 2011


On Fri, Nov 4, 2011 at 9:24 AM, Joshua Landau
<joshua.landau.ws at gmail.com> wrote:
> Non-lambdas work as expected, but a lambda inside a non-lambda still
> exhibits this behaviour.
> Conclusion:
> When setting defaults to keyword-only arguments in lambdas which are inside
> non-global scopes, cPython is unable to access the global scope and raises
> SystemError.

Fascinating! I did some introspection with this:

>>> def foo():
	a=1 # to make sure local variables do exist
	return (lambda *,keyword_only=global_variable: None)()

>>> dis.dis(foo)
  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (a)

  3           6 LOAD_CONST               2 ('keyword_only')
              9 LOAD_NAME                0 (global_variable)
             12 LOAD_CONST               3 (<code object <lambda> at
0x00FC7340, file "<pyshell#18>", line 3>)
             15 MAKE_FUNCTION          256
             18 CALL_FUNCTION            0
             21 RETURN_VALUE


>>> def foo():
	a=1
	return (lambda argument=global_variable: None)()

>>> dis.dis(foo)
  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (a)

  3           6 LOAD_GLOBAL              0 (global_variable)
              9 LOAD_CONST               2 (<code object <lambda> at
0x00F95E30, file "<pyshell#23>", line 3>)
             12 MAKE_FUNCTION            1
             15 CALL_FUNCTION            0
             18 RETURN_VALUE

Variations on the theme show that during compilation of foo, the name
is normally cemented as either a global or a local - but if it's
keyword-only, then a LOAD_NAME opcode is emitted. It's the code for
LOAD_NAME that looks for locals, which presumably a lambda doesn't
have.

ChrisA



More information about the Python-list mailing list