Printable string for 'self'

Fredrik Lundh fredrik at pythonware.com
Wed Mar 15 12:57:46 EST 2006


Don Taylor wrote:

> Fredrik Lundh wrote:
> > objects don't have names in Python, and the source is not part of
> > the running program.
> >
> > have you read this ?
> >
> >     http://effbot.org/zone/python-objects.htm
>
> I have now.  Thank you very much.
>
> "objects don't have names in Python": It appears from the code that
> Michael posted that objects can discover the names that are bound to
> themselves.  Is this true in general?

to the extent they have names, and the names exist in a namespace that
you can reach.  it might be time to quote myself here:

    Q. How can my code discover the name of an object?

    A. The same way as you get the name of that cat you found on your
    porch: the cat itself cannot tell you its name, and it doesn't really
    care -- so the only way to find out what it's called is to ask all your
    neighbours if it's their cat... and don't be surprised if you'll find that
    it's known by many names, or no name at all!

    from:

    http://www.python.org/doc/faq/programming.html#how-can-my-code-discover-the-name-of-an-object

    (fwiw, the current crop of stray cats in my neighbourhood are known
    as "sune" and "the big fat red one")

> "the source is not part of the running program" : Ok, but in my case I
> would have the source that corresponds to the running program available
> to me and the inspect module does appear to provide enough information
> for me to find the corresponding piece of the source code.  Is there
> something wrong with using the inspect module for this sort of work?

no, as long as you're aware that you're doing introspection, and that your
code won't run in all Python environments.

</F>






More information about the Python-list mailing list