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?
            Asked
            
        
        
            Active
            
        
            Viewed 309 times
        
    2
            
            
         
    
    
        Dimitris Fasarakis Hilliard
        
- 150,925
- 31
- 268
- 253
 
    
    
        11thHeaven
        
- 349
- 4
- 8
- 
                    1A listcomp compiles into pretty much the same thing as a `for`-loop; the only thing special is a `LIST_APPEND` bytecode operation that I don't think is used for anything else (if you actually wrote an `.append()` call yourself, that gets compiled as a generic method call, since Python could not generally be sure that the object it's being applied to is actually a list). – jasonharper Jun 09 '20 at 12:04
1 Answers
2
            
            
        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.
 
    
    
        Dimitris Fasarakis Hilliard
        
- 150,925
- 31
- 268
- 253