This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Enclosing scope not visible from within list comprehension
Type: behavior Stage: resolved
Components: Versions: Python 3.7
Status: closed Resolution: duplicate
Dependencies: Superseder: improper scope in list comprehension, when used in class declaration
View: 3692
Assigned To: Nosy List: eric.smith, serhiy.storchaka, woodscn, zach.ware
Priority: normal Keywords:

Created on 2019-02-21 23:25 by woodscn, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg336270 - (view) Author: Nathan Woods (woodscn) Date: 2019-02-21 23:25
The following code works in an interactive shell or in a batch file, but not when executed as part of a unittest suite or pdb:

from random import random
out = [random() for ind in range(3)]

It can be made to work using pdb interact, but this doesn't help with unittest.

Tested in Python 3.7.2
msg336271 - (view) Author: Zachary Ware (zach.ware) * (Python committer) Date: 2019-02-21 23:35
Can you attach a test file that shows the failure?
msg336277 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2019-02-22 03:04
I suspect Nathan is seeing this problem at class scope. This is a well known issue:

>>> class C:
...   from random import random
...   out = [random() for ind in range(3)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in C
  File "<stdin>", line 3, in <listcomp>
NameError: name 'random' is not defined

It is not related to the list comprehension, but to the class scope. See the last paragraph of

But I agree with Zach about needing an example that fails.
msg336278 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2019-02-22 05:02
This is a duplicate of issue3692.
Date User Action Args
2022-04-11 14:59:11adminsetgithub: 80251
2019-02-22 05:02:18serhiy.storchakasetstatus: open -> closed

superseder: improper scope in list comprehension, when used in class declaration

nosy: + serhiy.storchaka
messages: + msg336278
resolution: duplicate
stage: resolved
2019-02-22 03:04:54eric.smithsetnosy: + eric.smith
messages: + msg336277
2019-02-21 23:35:15zach.waresetnosy: + zach.ware
messages: + msg336271
2019-02-21 23:25:38woodscncreate