[Tutor] __cmp__() method examples?

Michael P. Reilly arcege@speakeasy.net
Fri, 7 Dec 2001 11:45:29 -0500


On Wed, Dec 05, 2001 at 09:35:47PM -0600, Rob McGee wrote:

> # now generate class instances -- this is always done automatically
> from string import uppercase
> for letter in uppercase:
>   execStr = letter + ' = Project("' + letter + '")'
>   # example -- 'A = Project("A")', 'Z = Project("Z")
>   exec(execStr)
> 
> {/code}
> 
> (Sorry about the exec's, but I really don't know another way to do what
> I want. I want these instances in the global namespace, and I need to
> know exactly what each one is named. At least I think I do. Suggestions
> about other ways to approach this would be welcomed, too. :) Like with
> no exec's, or with the instances in something other than globals(), how
> would I be able to retrieve and alter their properties?)

If you _really_ need have these as globals to that module, then you
can always import the module to a variable, then set the attributes
of that module:

# the name of the current module is in '__name__'
thismod = __import__(__name__)
from string import uppercase
for letter in uppercase:
  # same as module.A = Project("A")
  setattr(thismod, letter, Project(letter))

This is probably a better method than using exec.  But you might
also want to think about a different structure than global variables.

  -Arcege