Getting the name of an assignment
Adam Atlas
adam at atlas.st
Sat Dec 23 19:34:03 EST 2006
On Dec 23, 5:58 pm, "BJörn Lindqvist" <bjou... at gmail.com> wrote:
> On 23 Dec 2006 14:38:19 -0800, Adam Atlas <a... at atlas.st> 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? 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 guess you mean something like this:
>
> >>> olle = Person()
> >>> olle.name"olle"
>
> Instead of:
>
> >>> olle = Person("olle")
> >>> olle.name"olle"
>
> It is not possible without ugly hacks. What you could use instead is
> some kind of registry approach:
>
> reg = {}
> class Person:
> def __init__(self, name):
> self.name = name
> reg[name] = self
>
> >>> Person("olle")
> >>> reg["olle"].name"olle"
>
> I think there are thousand different ways you could solve it.
Yeah, I've thought of ways like that. I was just hoping to make the
syntax as minimal and Pythonic as possible.
I have the following working:
> import sys
>
> class c:
> def __init__(self):
> f = sys._getframe(1)
> names = [n for n in f.f_code.co_names if n not in f.f_locals]
> if len(names) > 0:
> name = names[0]
> print name
>
> a = c() # prints 'a'
> b = 'blah'
> b = c() # prints nothing
Question: too evil?
More information about the Python-list
mailing list