Where are list comprehensions implemented in CPython source code?

Viewed 223

I know that listobject.c contains the implementation of the list object in CPython but, how can I find the source code that handles list comprehensions?

1 Answers

There's isn't a specific function that handles list comprehensions, rather, a combination of opcodes is used to guide its creation.

If you take a look at the output of dis.dis for a comprehension, you can see these steps:

dis.dis('[i for i in ()]')

Disassembly of <code object <listcomp> at 0x7fc24c04a6f0, file "<dis>", line 1>:
  1           0 BUILD_LIST               0
              2 LOAD_FAST                0 (.0)
        >>    4 FOR_ITER                 8 (to 14)
              6 STORE_FAST               1 (i)
              8 LOAD_FAST                1 (i)
             10 LIST_APPEND              2
             12 JUMP_ABSOLUTE            4
        >>   14 RETURN_VALUE

I've only included the relevant disassembly for the list comprehension.

As you can see by looking at the names, this builds a list and then goes through the iterator supplied and appends values. You can open ceval.c and simply search for each opcode if you need a more detailed view of what is performed for each of them.

Related