[Tutor] introspection

Dave Angel davea at davea.name
Fri May 8 05:45:33 CEST 2015


On 05/07/2015 11:23 PM, Alex Kleider wrote:
> On 2015-05-07 19:10, Dave Angel wrote:
>
>>> def get_name(localmap, item):
>>>      """As suggested.
>>>      Returns 'a' name, not necessarily 'the' name."""
>>>      for name in localmap:
>>>          if localmap[name] == item:
>>
>> This is not likely to be what was intended.  You want
>>            if localmap[name] is item:
>> That can identify if one of the names happens to be bound to the SAME
>> object being examined.  Rather than one that happens to have the same
>> value.
>
> Correction noted.  Thank you for that.  The distinction is important.
> ('==' vs 'is')
>

You also only showed it working on module globals.  (For code at 
top-level, locals() returns the same as globals() )

You could also try it inside functions, where locals() really makes 
sense as a name.  And you could try it in a nested function where there 
may very well be non-locals (eg. closure items) that aren't local or global.

But more interestingly, you could try it on items of a list, or members 
of a dictionary, where there's no name at all associated with the object.


-- 
DaveA


More information about the Tutor mailing list