Search code examples
pythonclassdictionaryscopecpython

undefined variable does not raise error if in scope of iteration with that name defined


Using CPython 3.8.2+ (984a5, the following code executes without raising an error. The result is a dictionary which prints as if it has values that are instances with the same value stored.

class Foo(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return name  # this is undefined (missing `self.`)


optable = dict()
for name in ['a', 'b']:
    optable[name] = Foo(name)
print(optable)
print(optable['a'].name)
print(optable['b'].name)

This script prints

{'a': b, 'b': b}
a
b

Unexpectedly, both representations are printed, and are "b".

Could this be a CPython bug?


Solution

  • As said in the comments, make sure to return the name that belongs to each instance of Foo

        def __repr__(self):
            return self.name
    

    to prevent returning the global name instead.

    Also, make sure to use the correct method to represent the object