how to get a class instance name during creation?

Aaron "Castironpi" Brady castironpi at
Sat Oct 4 08:14:07 CEST 2008

On Oct 3, 1:46 pm, Bruno Desthuilliers
<bdesth.quelquech... at> wrote:
> dmitrey a écrit :
> > hi all,
> > I have a code
> > z = MyClass(some_args)
> > can I somehow get info in MyClass __init__ function that user uses "z"
> > as name of the variable?
> > I.e. to have __init__ function that creates field with value
> > "z".
> This has been debated to hell and back. To make a long story short, here
> are two common use cases:
> x = MyClass()
> y = x
> del x
> objects = [MyClass() for i in range(100)]
> If you can come with a meaningfull answer to "what's *the* name of any
> of the MyClass instance(s)" in both cases, then please let us know...

Hmmm, just thinking:

What about a function:

autoname( 'x= MyClass' )

which calls exec as well as determines the name?  That could use
'code' and 'ast' modules and 'parse', or just take the first \w
characters, assuming assignment, or:

autoname( 'x', MyClass() )

which executes assignment and sets an attr or calls a method on the
second arg.

More information about the Python-list mailing list