-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
1
  • 3
    Don't do that, either use a list or dictionary. Commented Nov 6, 2014 at 14:41

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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)

4 Comments

For a simple case like this, I would not recommend mucking with globals() or locals(). Just use a list.
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.
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.
@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.
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

1 Comment

I suppose that might be easier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.