1

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?

0 _
  • 10,524
  • 11
  • 77
  • 109
  • 1
    `name` is pulled from the global scope, it's defined and assigned by the `for` loop. Try `for item in ['a', 'b']:` instead. – metatoaster Apr 20 '20 at 04:37
  • Additional [discussion](https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops). – metatoaster Apr 20 '20 at 04:39
  • 1
    `name` is *not* undefined, Python scoping rules look first at local, then enclosing, and finally global (and built-in) namespace. `name` exists in the global namespace – juanpa.arrivillaga Apr 20 '20 at 06:02

1 Answers1

0

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

Pynchia
  • 10,996
  • 5
  • 34
  • 43