Method to give name of class instance?

Alex Martelli aleaxit at yahoo.com
Mon Apr 30 03:48:35 EDT 2001


"Timothy L. Robertson" <timothyr at timothyr.com> wrote in message
news:3aecaef9.340108430 at news.mindspring.com...
> Hi Everyone,
>
> I've been enjoying learning Python very much, but have hit a little
> snag.  I want a way to find out the name of a class instance from a
> method.  eg.
>
> >>>classinstance=MyClass()
> >>>classinstance.myname()
> 'classinstance'
>
> Is there a way to do this?

Python's Frequently Asked Questions (FAQ) are a very useful resource.
You are likely to find reasonable answers to most questions which ARE
frequently asked, such as this one.  Specifically, see
    http://www.python.org/doc/FAQ.html#4.97

What that FAQ doesn't say is that you CAN easily write functions
that will look for (all occurrences/first occurrence) of a certain
value (AKA object) in a set of variables (which is, after all, just
a dictionary).  For example:

def oneName(object, vars):
    for name, value in vars.items():
        if value is object: return name
    return None

to be called as oneName(classinstance, vars()) if you need "just
any name" (be it local or global), oneName(classinstance, locals())
if you need specifically a local variable name for the instance,
oneName(classinstance, globals()) if you need a global variable
name in the current module, oneName(classinstance, dir(amod)) if
you need it in module object amod, and so on.

It *IS* possible to play "black magic" tricks so the function
will be able to use the *caller's* locals or globals by default,
but "black magic as a way of life" is *NOT* a programming
approach that can be recommended (either in Python, or in any
other language)...


Alex






More information about the Python-list mailing list