-3

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 p1, p2, 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
Rick
  • 43,029
  • 15
  • 76
  • 119

3 Answers3

6

It's called a list:

p = [Point(1, 1), Point(2, 2), Point(3, 3)]

Now p[0] is your p1, et cetera.

p = [Point(i, i) for i in range(1, 1000)]
isinstance(p[500], Point)  # True
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

you could store them as keys in a dictionary

vars_dict = {}
for i in range(1,1000):
    vars_dict['p{}'.format(i)] = Point(i, i)
isinstance(vars_dict['p500'], Point) # True

or in an iterable as @RemcoGerlich did

dm03514
  • 54,664
  • 18
  • 108
  • 145
1

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)
wim
  • 338,267
  • 99
  • 616
  • 750
bgusach
  • 14,527
  • 14
  • 51
  • 68
  • 1
    For a simple case like this, I would not recommend mucking with `globals()` or `locals()`. Just use a list. – Kevin Nov 06 '14 at 14:42
  • 2
    But if you do that, you are using your variables namespace as if it were itself a variable. This usually leads to regret later on. – RemcoGerlich Nov 06 '14 at 14:42
  • This is probably the correct answer to my actual question, however, the better way to do what I'm trying to do is probably to use a list as suggested by RemcGerlich. – Rick Nov 06 '14 at 14:42
  • 1
    @RemcoGerlich This answers the question, and it is interesting to know that you can modify the current lexical scope dynamically. However, as I stated in the answer, it is a very poor solution. – bgusach Nov 06 '14 at 14:45