Creating alot of class instances?

Steven D'Aprano steve at
Mon Jul 6 05:46:41 CEST 2009

On Sun, 05 Jul 2009 19:27:25 -0700, kk wrote:

> Hi
> Thank you so much for wonderful tips and suggestions.
> I also found a solution to dynamic naming of the instances(I think). It
> does not sound like a very secure method but since my application will
> be just processing data one way I think it might be alright. I will
> compare to the list and dictionary methods.
> globals()["Some_Instance_Name"]

You're fighting the computer instead of working with it. That's the Wrong 
Way to solve the problem -- you're doing more work than needed, for 
little or no benefit.

My bet is, you have code that looks something like this:

for i in range(N):  # N comes from somewhere else
    # Create a new variable
    globals()["Some_Instance_Name%s" % i] = instance()

# Do something with the variables
for i in range(N):
    # Look up the variable
    x = globals()["Some_Instance_Name%s" % i]

Am I close?

That's the Wrong Way to do it -- you're using a screwdriver to hammer a 
nail. The right way to work with an unknown number of data elements is to 
put them in a list, and process each element in the list, not to try 
giving them all unique names. The only reason for using named variables 
is so you can use the name in source code:

my_value = Some_Instance87 + Some_Instance126

But you can't do that, because you don't know how many instances there 
are, you don't know whether to write Some_Instance87 or Some_Instance125 
or Some_Instance19.

So instead, do something like this:

instances = []
for i in range(N):
    # Create a new instance and store it for later
    instances.append( instance() )

# Later on:
for x in instances():


More information about the Python-list mailing list