On Thu, 24 Sep 2009 01:15:14 +0100, andrew cooke <and...@acooke.org> wrote:


This is a bit vague, I'm afraid, but is there any way for me to take
code like:

   a = Foo()
   beta = Bar()

and somehow attach the string "a" to the Foo instance and "beta" to
the Bar instance.  At some later point in the program I want to be
able to look at the Bar instance and say to the user "this was called
beta in your routine".

Fundamentally, not without the user's collusion.  The best you can do
if you don't have access to the right namespace dictionary is to pass
the object a name explicitly:

class Foo(object):
  def __init__(self, name):
    self.name = name
    # ...and anything else

a = Foo('a')

The problem is that objects can have more than one name at a time,
and that assignment targets can be more than simple names.  What
would you want to say about:

eggs[42] = Foo()
beans['spam'] = Foo()
chips.spam = Foo()
spam[eggs.beans['chips']] = Foo()
spam.append(Foo())

and so on.

The thing to google for is Python's assignment model, because it's
probably not what you think it is.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to