Rick Teachey Rick Teachey - 16 days ago 4x
Python Question

Dynamically define variable names

I have written some classes I would like to test by creating multiple instances of my classes. I would like those instances to have names following the pattern

, etc:

p1 = Point(1,1)
p2 = Point(2,2)
p3 = Point(3,3)

Is there a way to do this quickly for a lot of variables? Something like this:

for i in range(1,1000):
*magic goes here*
isinstance(p500, Point) # True


You can modify the current scope changing globals()

For instance:

globals()['p234'] = Point(1, 2)
print p234

This is however, an extremely poor quality approach: hard to understand, maintain, creates a horrible scope polution and it is slow (although this does not probably matter). Use a proper data container, I would suggest a list:

points = [Point(i, i) for i in xrange(500)]
assert isinstance(p[-1], Point)

This way you can do an assert on every object like:

points = [Point(i, i) for i in xrange(500)]
for point in points:
    assert isinstance(point, Point)