diff options
author | Pablo Galindo <Pablogsal@gmail.com> | 2019-10-14 04:18:05 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-10-14 04:18:05 (GMT) |
commit | fd5c414880b2e05720b9cf14ab0b0d7ae2b7d925 (patch) | |
tree | eedbde8610788bd4ea9577b0aa94f1af10cde089 /Lib | |
parent | 8a6cbf8adb68aa2c43a48769af92e50d5ca1539d (diff) | |
download | cpython-fd5c414880b2e05720b9cf14ab0b0d7ae2b7d925.zip cpython-fd5c414880b2e05720b9cf14ab0b0d7ae2b7d925.tar.gz cpython-fd5c414880b2e05720b9cf14ab0b0d7ae2b7d925.tar.bz2 |
bpo-38469: Handle named expression scope with global/nonlocal keywords (GH-16755)
The symbol table handing of PEP572's assignment expressions is not resolving correctly the scope of some variables in presence of global/nonlocal keywords in conjunction with comprehensions.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/test/test_named_expressions.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/Lib/test/test_named_expressions.py b/Lib/test/test_named_expressions.py index b1027ce..01e26c8 100644 --- a/Lib/test/test_named_expressions.py +++ b/Lib/test/test_named_expressions.py @@ -1,6 +1,7 @@ import os import unittest +GLOBAL_VAR = None class NamedExpressionInvalidTest(unittest.TestCase): @@ -470,5 +471,49 @@ spam()""" self.assertEqual(ns["x"], 2) self.assertEqual(ns["result"], [0, 1, 2]) + def test_named_expression_global_scope(self): + sentinel = object() + global GLOBAL_VAR + def f(): + global GLOBAL_VAR + [GLOBAL_VAR := sentinel for _ in range(1)] + self.assertEqual(GLOBAL_VAR, sentinel) + try: + f() + self.assertEqual(GLOBAL_VAR, sentinel) + finally: + GLOBAL_VAR = None + + def test_named_expression_global_scope_no_global_keyword(self): + sentinel = object() + def f(): + GLOBAL_VAR = None + [GLOBAL_VAR := sentinel for _ in range(1)] + self.assertEqual(GLOBAL_VAR, sentinel) + f() + self.assertEqual(GLOBAL_VAR, None) + + def test_named_expression_nonlocal_scope(self): + sentinel = object() + def f(): + nonlocal_var = None + def g(): + nonlocal nonlocal_var + [nonlocal_var := sentinel for _ in range(1)] + g() + self.assertEqual(nonlocal_var, sentinel) + f() + + def test_named_expression_nonlocal_scope_no_nonlocal_keyword(self): + sentinel = object() + def f(): + nonlocal_var = None + def g(): + [nonlocal_var := sentinel for _ in range(1)] + g() + self.assertEqual(nonlocal_var, None) + f() + + if __name__ == "__main__": unittest.main() |