[Tutor] introspection
Alex Kleider
akleider at sonic.net
Fri May 8 03:50:28 CEST 2015
On 2015-04-21 16:48, Cameron Simpson wrote:
> But it would not be schizophrenic to write a function that returned a
> name arbitrarily, by inspecting locals(). It depends whether you only
> need a name, or if you need "the" name.
>
> Write yourself a "find_name_from_locals(local_map, value)" function
> that reports. That will (a) get you a partial answer and (b) cement in
> your mind what is possible and why. Easy and useful!
>
> Cheers,
> Cameron Simpson <cs at zip.com.au>
Well I finally got around to tackling this little challenge and you are
right:
It was illuminating.
For what it's worth, here's the code that made the light go on:
#!../venv/bin/python3
# -*- coding: utf-8 -*-
# vim: set file encoding=utf-8 :
#
# file: 'getname.py'
"""
Following through on:
Write yourself a "find_name_from_locals(local_map, value)" function that
reports. That will (a) get you a partial answer and (b) cement in your
mind what is possible and why. Easy and useful!
Cheers, Cameron Simpson <cs at zip.com.au>
"""
a = 'Alex'
j = 'June'
ssn = 681769931 # Totally ficticious!
# print(locals())
def get_name_1st_version(item):
"""What I naively thought would work."""
for name in locals():
if name == item:
return name
def get_name(localmap, item):
"""As suggested.
Returns 'a' name, not necessarily 'the' name."""
for name in localmap:
if localmap[name] == item:
return name
if __name__ == '__main__': # code block to run the application
# First attempt:
print(get_name_1st_version(a))
print(get_name_1st_version(j))
print(get_name_1st_version(ssn))
print(get_name_1st_version('Alex'))
print(get_name_1st_version('June'))
print(get_name_1st_version(681769931))
# Second attempt:
localmap = locals()
# Lesson learned: must use localmap created within the namespace
# under scrutiny.
print(get_name(localmap, a))
print(get_name(localmap, j))
print(get_name(localmap, ssn))
print(get_name(localmap, 'Alex'))
print(get_name(localmap, 'June'))
print(get_name(localmap, 681769931))
More information about the Tutor
mailing list