Scope of variable in for loop python

Viewed 26

I am quite puzzled with this python3 behavior, and have no clue how to fix it. Consider the following code

class Foo:
    class Bar:
        def __init__(self):
            self.one = 1
            self.two = ['empry']
            self.hosts = ['un', 'deux']

    _bar = Bar()

    test = [
        {'deviceId': _bar.one
        }
        for host in _bar.hosts
    ]

d = Foo()
print (d.test)

If I run it using python2, it shows [{'deviceId': 1}, {'deviceId': 1}] If I run it using python3 (Python 3.8.10), I have

Traceback (most recent call last):
  File "toot.py", line 1, in <module>
    class Foo:
  File "toot.py", line 10, in Foo
    test = [
  File "toot.py", line 11, in <listcomp>
    {'deviceId': _bar.one
NameError: name '_bar' is not defined

This is due to the usage of _bar in the for loop. The usage of _bar in for host in _bar.hosts is valid ...

(I know this code use class attribute .... but my request is about variable scope in for loop).

Why this _bar variables is not in the variables scope ?

Note that if I build the test attribute like this, python3 is happy

test = []
for host in _bar.hosts:
    test.append({'deviceId': _bar.one})
0 Answers
Related