finding name of instances created
steven.bethard at gmail.com
Fri Jan 21 21:46:40 EST 2005
> Steven Bethard wrote:
>>>Using the method suggested by Steven Bethard, I *almost* got it
>>>the way I would like.
>>It looks like you want PrivateClass.dict updated every time that
>>globals() is updated.
> yes, that is what I would like to do.
>>You can just use globals directly instead:
>>py> class PrivateClass(object):
>>... def __init__(self, globals):
>>... self.globals = globals
>>... def apparently_simple_method(self):
>>... for name, value in self.globals.iteritems():
>>... if value is self:
>>... print "instance %s called not so simple" % name
>>py> def public_class():
>>... return PrivateClass(globals())
>>py> alpha = public_class()
>>instance alpha called not so simple
>>py> beta = public_class()
>>instance beta called not so simple
> That's exactly what I was looking for; thank you!
>>On the other hand, the iteration in
>>PrivateClass.apparently_simple_method has a very bad code smell...
> I'm not sure what you mean...
> Is it because it makes use of information that is
> exterior to the class, which is not passed as a parameter
> to the method?
> [feel free to ignore this question if you want; you have
> already helped me tremendously!!!]
There's a couple things I don't like about it:
(1) Generally, I don't like passing globals() around. It's probably
okay in this scenario though because if you want to have the user code
in a different module, you can do something like:
(2) The really bad code smell however is having to iterate through all
the values in globals to find the key you're looking for... Especially
when you have to check the type of each item... In a perfect world, you
would already have a PrivateClass->name mapping somewhere and this
should be a simple dict lookup instead of an iterative search... See my
other post about potentially pre-processing your user input to see how
you can convert the iteration to a simple attribute lookup.
More information about the Python-list