[New-bugs-announce] [issue19611] inspect.getcallargs doesn't properly interpret set comprehension code objects.

Ned Batchelder report at bugs.python.org
Fri Nov 15 13:03:03 CET 2013


New submission from Ned Batchelder:

In 2.7, set comprehensions are compiled to code objects expecting an argument named ".0".  This convention is also used for the unnamed arguments needed by tuple arguments.  inspect.getcallargs understands the tuple argument case, but not the set comprehension case, and throws errors for correct arguments.

This is also true for generator expressions and dictionary comprehensions.

Demonstration:

#-----
import inspect
import sys
import types

def make_set():
    return {z*z for z in range(5)}

print(make_set())

# The set comprehension is turned into a code object expecting a single
# argument called ".0" with should be an iterator over range(5).
if sys.version_info < (3,):
    setcomp_code = make_set.func_code.co_consts[1]
else:
    setcomp_code = make_set.__code__.co_consts[1]
setcomp_func = types.FunctionType(setcomp_code, {})

# We can successfully call the function with the argument it expects.
print(setcomp_func(iter(range(5))))

# But inspect can't figure that out, because the ".0" argument also means
# tuple arguments, which this code object doesn't expect.
print(inspect.getcallargs(setcomp_func, iter(range(5))))

#-----



When run on Python 3.3, this produces:

    {0, 1, 4, 16, 9} 
    {0, 1, 4, 16, 9}
    {'.0': <range_iterator object at 0x10834be70>}

When run on Python 2.7, it produces:

    set([0, 1, 4, 16, 9])
    set([0, 1, 4, 16, 9])
    Traceback (most recent call last):
      File "foo.py", line 17, in <module>
        print(inspect.getcallargs(setcomp_func, iter(range(5))))
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 935, in getcallargs
        assign(arg, value)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 922, in assign
        raise ValueError('too many values to unpack')
    ValueError: too many values to unpack

----------
components: Library (Lib)
messages: 202944
nosy: nedbat
priority: normal
severity: normal
status: open
title: inspect.getcallargs doesn't properly interpret set comprehension code objects.
versions: Python 2.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19611>
_______________________________________


More information about the New-bugs-announce mailing list