Getting the name of an assignment
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sat Dec 23 19:48:57 EST 2006
On Sat, 23 Dec 2006 14:38:19 -0800, Adam Atlas wrote:
> Is it possible for an object, in its __init__ method, to find out if it
> is being assigned to a variable, and if so, what that variable's name
> is?
What should the variable name be set to if you do one of the following?
john = eric = graham = terry = Named_Instance()
some_list = [None, 1, "string", Named_Instance()]
fred = Named_Instance(); barney = fred; del fred
Name assignment is not a one-to-one operation. An object can have no name,
one name or many names. If your code assumes such a one-to-one
relationship between names and objects, it is wrong.
> I can think of some potentially ugly ways of finding out using
> sys._getframe, but if possible I'd prefer something less exotic.
> (Basically I have a class whose instances, upon being created, need a
> 'name' property, and if it's being assigned to a variable immediately,
> that variable's name would be the best value of 'name'; to make the code
> cleaner and less redundant, it would be best if it knew its own name
> upon creation, just like functions and classes do, without the code
> having to pass it its own name as a string.)
I suggest rethinking your data model, and accept that the name
attribute of an object is not necessarily the same as the name it is
bound to.
If you still want a convenience function that names the object and binds
it to a name at the same time, try something like this:
def Make_A_Named_Instance(name, *args, **kwargs):
globals()[name] = Named_Instance(*args, **kwargs)
globals()[name].name = name
You might be tempted to replace globals() with locals() in the above.
Don't -- it doesn't generally work:
http://docs.python.org/lib/built-in-funcs.html
--
Steven.
More information about the Python-list
mailing list