[Python-porting] co_names behavior change

Piet van Oostrum piet-l at vanoostrum.org
Mon Apr 8 15:46:26 EDT 2019


Tom Ekberg wrote:
 > 
 > My question to this group:
 > 
 > Do you have knowledge of the different contents of __code__.co_names between Python 2.7 and Python
 > 3.5? I'm expecting that this is a difference that is documented somewhere.
 > 

The difference is that in Python 3 a (list) comprehension is compiled into an anonymous function, to prevent the leaking of the control variable (x in this case). The base from which the list is constructed (i.e. the expression after 'in') is given as the argument to this function, so any variable in that part appears in co_names. But the rest of the comprehension is part of that anonymous function, so in this case the names 'realname' and 'user_realnames' are not local to your function 'f', but of the anonymous function.

In Python 2, the list comprehension was compiled inline.
-- 
Piet van Oostrum <piet-l at vanoostrum.org>
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]



More information about the Python-porting mailing list