Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested generator expressions can't access parent scope in set and dict comprehensions (unlike cPython 2.7) #819

Open
JamesParrott opened this issue Jun 15, 2022 · 1 comment

Comments

@JamesParrott
Copy link

JamesParrott commented Jun 15, 2022

Hi there,
I have searched, but apologies if this is a known bug. (I know I can and should just code this as "if key in chars" but this is just an MRE. I wanted to be able to use any with a more useful iterable of functions to check much more general conditions than equality):

keys = 'abc'
chars = 'bcd'
print( {key for key in keys if any(key==x for x in chars)})
>py27 filtered_set_comp.py
set(['c', 'b'])

>ipy filtered_set_comp.py
NameError: global name 'key' is not defined

List comprehensions don't have this issue, as in Python 2 they leak all their variables into their parent scope anyway. Set and dict comprehensions don't leak variables out into their local scope. A work around is coercing a generator expression to the desired type:

set(key for key in d if any(key==x for x in chars))

dict((key, v) for (key, v) in d.items() if any(key==x for x in chars))

dict_and_set_comprehensions_iron_python_2_sub_scope_bug.zip

@slozier
Copy link
Contributor

slozier commented Jun 15, 2022

Thanks for the report! May be related to IronLanguages/ironpython3#817 (which was fixed in IronPython 3).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants