Little Q: how to print a variable's name, not its value?

Ron_Adam radam2 at tampabay.rr.com
Thu Mar 31 13:10:22 EST 2005


On 30 Mar 2005 08:43:17 GMT, Duncan Booth
<duncan.booth at invalid.invalid> wrote:

>Here is a rough attempt at printing the names of a variable. It will pick
>up several names where appropriate, but deliberately doesn't attempt to
>get all possible names (as you say, that could result in endless loops).
>In particular, for the Fred=5/John=8/Winner=8 example it will only find
>one of John or Winner since it only picks at most one match from each dict 
>or list. It doesn't yet manage to correctly lookup attributes (e.g. slots) 
>when they aren't stored in a __dict__, nor does the output distinguish
>between dictionary keys and values (so encodings.cp437.encoding_map[8]
>below actually refers to the key not the value).


Here's what I've been working on.  It still has some glitches in it
but I think it has potential as a instructional/diagnostict tool

I'm going to repost this with the source as it's own topic, maybe it
can be developed further.  :)

Cheers,
Ron



IDLE 1.1.1c1      ==== No Subprocess ====
>>> from pnames import pnames
>>> pnames()
[globals]
     __builtins__ --> <module> 
     __doc__ --> <docstring> 
     __file__ --> C:\Python24\Lib\idlelib\idle.pyw 
     __name__ --> __main__ 
     idlelib --> <module> 
     pnames --> <function> 
Paused
>>> John = 8
>>> Fred = 6
>>> Winner = John
>>> players = [John, Fred]
>>> pnames()
[globals]
     __builtins__ --> <module> 
     __doc__ --> <docstring> 
     __file__ --> C:\Python24\Lib\idlelib\idle.pyw 
     __name__ --> __main__ 
     Fred --> 6 
     idlelib --> <module> 
     John --> 8 
     players --> [8, 6] 
     pnames --> <function> 
     Winner --> 8 
Paused

Both winner and John point to the litteral '8', but since the number
'8' can never be changed, it doesn't matter,  but you can look up the
number '8' and find both John and Winner, but changing one, doesn't
change the other.


>>> John = 9
>>> pnames()
[globals]
     __builtins__ --> <module> 
     __doc__ --> <docstring> 
     __file__ --> C:\Python24\Lib\idlelib\idle.pyw 
     __name__ --> __main__ 
     Fred --> 6 
     idlelib --> <module> 
     John --> 9 
     players --> [8, 6] 
     pnames --> <function> 
     Winner --> 8 
Paused

Winner didn't change it's value.


>>> scores = players
>>> pnames()
[globals]
     __builtins__ --> <module> 
     __doc__ --> <docstring> 
     __file__ --> C:\Python24\Lib\idlelib\idle.pyw 
     __name__ --> __main__ 
     Fred --> 6 
     idlelib --> <module> 
     John --> 9 
     players --> [8, 6] <-- scores
     pnames --> <function> 
     scores --> [8, 6] <-- players
     Winner --> 8 
Paused
>>> 

Here, players and scores are both mutable, changeing them will change
the other and so it shows that the list [8,6] has more than one name.


Cheers,
Ron




More information about the Python-list mailing list