How to get an object's name as a string?

alex23 wuwei23 at gmail.com
Wed Oct 29 10:09:23 EDT 2008


On Oct 29, 11:31 pm, ShanMayne <shang... at gmail.com> wrote:
> However this does not help me to use the reference/name of an object I
> imported instead of created.

I've never really understood these requests (and they come up a lot).
Unless you're doing a '*' import, you'll already know the bound names
of the objects you're importing. If you -are- doing a '*' import and
you -don't- know what objects are being imported, how will you refer
to the object to find out its name?

However, maybe one of the following examples will be of use.

Assume a module 'items' that contains:

    a = 1
    b = 'string'

The best way would be to use the module as it is intended, as a
namespace:

    >>> import items
    >>> names = [x for x in dir(items) if not '__' in x] # ignore
special objects
    >>> names
    ['a', 'b']
    >>> one = getattr(items, names[0])
    >>> two = getattr(items, names[1])
    >>> one
    1
    >>> two
    'string'

Another way is to look through the variables in the current scope:

    >>> before = set(locals())
    >>> before.add('before') # you want to ignore this object too
    >>> from items import *
    >>> names = list(set(locals()).difference(before))
    >>> names
    ['a', 'b']
    >>> one = locals()[names[0]]
    >>> two = locals()[names[1]]
    >>> one
    1
    >>> two
    'string'

Do either of these help with your problem?



More information about the Python-list mailing list