[Tutor] introspection
Alex Kleider
akleider at sonic.net
Mon Apr 20 18:55:41 CEST 2015
On 2015-04-20 09:15, Joel Goldstick wrote:
> On Mon, Apr 20, 2015 at 11:24 AM, Alex Kleider <akleider at sonic.net>
> wrote:
>> Does python provide the introspective ability to retrieve the name to
>> which
>> an object is bound?
>>
>> For example:
>> $ python3
>> Python 3.4.0 (default, Apr 11 2014, 13:05:18)
>> [GCC 4.8.2] on linux
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>
>>>>> a = 69
>>>>> print("Identifier <{}> is bound to {}.".format(a.__name__, a))
>>
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> AttributeError: 'int' object has no attribute '__name__'
>>
>>
> An object can be bound to multiple names. Within a namespace you can
> use locals to see names, then compare various names like so:
>>
>>>> a = 3
>>>> b = 6
>>>> c = a
>>>> locals()
> {'a': 3, 'c': 3, 'b': 6, '__builtins__': <module '__builtin__'
> (built-in)>, '__package__': None, '__name__': '__main__', '__doc__':
> None}
>>>> a is b
> False
>>>> a is c
> True
Showing my desired use case might make my question more understandable:
def debug(var_name):
if args["--debug"]:
print("Identifier <{}> is bound to: {}"
.format(var_name.__name__, repr(var_name)))
I don't think the built in locals() can help me.
Thanks all the same.
Alex
More information about the Tutor
mailing list