Parsing & question about usages off classes!

Chermside, Michael mchermside at ingdirect.com
Mon Nov 4 14:13:35 EST 2002


> Ok. I am trying a different approach. But I am still having problems.
> 
> I want to create several new list. The name off the new lists will come 
> from another list. That way I can create several lists, depending on the 
> data received from logfiles. Is that possible ?
> 
> Or isnt that a good idea either ? :)

It isn't a good idea. In fact, ANY time that you plan to create a
bunch of different things (be they classes, instances, or WHATEVER)
and store them in variables with different names, you're going
about it wrong.

You see, if you make a bunch of things and store them in the 
variables "foo_1", "foo_2", "foobar", etc, then you'll have to
write code which "magically" knows what variable names to call.
Instead of that, what you want is to create either a list or a
dictionary which contains ALL the values, then the code that you
write can use that dictionary.

Here's an example:

   # What you _think_ you want (**DOES NOT WORK**)
   for i in range(3):
       myFoo + "_" + i = Foo()   # DOES NOT WORK
   print myFoo_0
   print myFoo_1
   print myFoo_2

   # What you _really_ want:
   myListOfFoos = []
   for i in range(3):
       myListOfFoos.append( Foo() )
   for i in range(3):
       print myListOfFoos[ i ]

Or an example which uses a dictionary:

   # What you _think_ you want (**DOES NOT WORK**)
   while more_users_exist():
       u = getNextUser()
       user + "_" + u.name = u.data
   user_Fred.analysize()
   user_Tracy.analysize()
   user_Kim.analysize()


   # What you _really_ want:
   users = {}
   while more_users_exist():
       u = getNextUser()
       users[ u.name ] = u.data

   for name in users:
       users[ name ].analysize()

Really, I assure you... unless you are effectively expanding
Python itself, you will find that you NEVER want a bunch of
specially named variables... you want some sort of data 
structure instead.

In fact, if you DO work on Python itself, you will find that
whenever[1] you DO create a bunch of variables, Python is
really creating a dictionary behind the scenes! Try typing
"locals()" or "globals()" sometime and see what you get,
or take an object you created and type "print x.__dict__".

So even the innards of Python itself follows this dictum.

-- Michael Chermside

[1] - for optimization reasons, there is one exception I
know of... local variables within a function are treated
AS IF they were in a dictionary, but they aren't actually.




More information about the Python-list mailing list