Printing Varable Names Tool.. Feedback requested.

R

Ron_Adam

Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error. I haven't tested
it on linux yet either. It could be something with my python
install.(?)

Anyway, here's the source with an example output. I'm still not sure
what to call it. Pnames stands for printnames, but if you think of
something better let me know.

Some things I think will be good is shortening long output such as
lists and dictionaries to '[...]' or '[:] or a few chars at the
beginning and end with '...' in the middle. I think it's important to
keep the output short and readable.

Any suggestions would be apreciated. :)

Ron


IDLE 1.1.1c1 ==== No Subprocess ====[globals]
__builtins__ --> <module>
__doc__ --> <docstring>
__file__ --> C:\Python24\Lib\idlelib\idle.pyw
__main__ --> <module>
__name__ --> __main__
g --> 45
glist --> ['a changed', 'list'] <-- test2:a
h --> 45
idlelib --> <module>
pnames --> <function>
sys --> <module>
test1 --> <function>
test2 --> <function>
test2.at1 --> [True] <-- test2:aaa
[test1]
t --> ['altered'] <-- test2:w
[locals:test2]
a --> ['a changed', 'list'] <-- globals:glist
aaa --> [True] <-- globals:test2.at1
w --> ['altered'] <-- test1:t
Paused


#---start---

# pnames.py
"""
A utility to print the value of variables for
debugging purposes.

To use: import prnames and insert prnames.prnames()
in the program where you want to examin names.
Pressing any key will continue.

Author: Ronald Adam
"""

import sys
if __name__ is not '__main__':
import __main__

def pnames():
"""
View
"""
objdict = {} # Collect references to object.
namelist = [] # List of names and values by frame.
n = 1
name = None
while name!= 'runcode':
# Move up in the frames to gather name data.
# until the application global frame is reached.
name = sys._getframe(n).f_code.co_name
if name != 'runcode': # This keeps it out of idle's name
space.
namelst = [name,[]]
namespace = sys._getframe(n).f_locals
keys = namespace.keys()
# Get all the names in this frame.
for k in keys:
try:
trash = objdict[id(namespace[k])][name]
except:
try:
objdict[id(namespace[k])][name]=[k]
except:
objdict[id(namespace[k])]={name:[k]}
else:
objdict[id(namespace[k])][name].append(k)
namelst[1].append((k,namespace[k],id(namespace[k])))
#namelist.append(namelst)
#try:
attribs = None
try:
attribs = namespace[k].func_dict
except:
pass
if attribs:
for att in attribs:
attname = k+'.'+att
try:
trash = objdict[id(attribs[att])][attname]
except:
try:

objdict[id(attribs[att])][name]=[attname]
except:

objdict[id(attribs[att])]={name:[attname]}
else:

objdict[id(attribs[att])][name].append(attname)

namelst[1].append((attname,attribs[att],id(attribs[att])))
namelist.append(namelst)

n += 1
# Now print what we collected.
namelist.reverse() # Reverse it so we have globals at the
top.
tab = 0
for gname, group in namelist:
# Sort it.
def sortnocase(stringlist):
tupleList = [(x[0].lower(), x) for x in stringlist]
tupleList.sort()
return [x[1] for x in tupleList]
group = sortnocase(group)
if gname == chr(63): # Idle uses this as name as
app-globals.
gname = 'globals'
if gname == namelist[-1:][0][0]:
gname = 'locals:'+gname # Indicate locals group.
print '%s[%s]'%(' '*tab, gname)
tab += 1

for name, obj, objid in group:
# Print the varable name
print ' '*tab,name,'-->',

# Remove & replace a lot of clutter as we print it.
# List other names pointing to mutable objects.
if name == '__doc__':
obj = '<docstring>'
if 'module' in str(obj): # These remove clutter
obj = '<module>' # More probably needs to be
if 'function' in str(obj): # done here.
obj = '<function>'

# Print the object
print obj,

# Print the other names pointing to
# the object.
obj2 = ''
if type(obj) not in [int, str, float, bool, tuple] \
and obj not in [True, False, None]:
for obj in objdict[objid].keys():
name2 = objdict[objid][obj]
n = 0
if len(name2):
for name3 in name2:
if obj == chr(63):
obj = 'globals'
if name3 != name:
if n>0:
obj2 += ', '
if obj != gname:
obj2 += obj+':'+name3
else:
obj2 += name3
n += 1

if len(obj2)>0:
obj2 = '<-- '+obj2
print obj2
raw_input( 'Paused')

def test1():
global g
t = g
t = [9]
test2.at1 = [True]
test2(t)

def test2(w):
a = glist
aaa = test2.at1
test2.at1[0] = True
a[0] = 'a changed'
w[0] = 'altered'
pnames()


if __name__ == '__main__':
# Make a few globals to see.
g = 45
h = g
glist = ['just a','list']

# Put an attribute on a function
# to find.
test2.at1 = 25

# Run test function.
test1()

#---end---
 
R

Ron_Adam

Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error. I haven't tested
it on linux yet either. It could be something with my python
install.(?)


Here's the error I'm getting from the python command window.



C:\ron\rondev\pythonmods>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "pnames.py", line 28, in pnames
name = sys._getframe(n).f_code.co_name
ValueError: call stack is not deep enough
 
R

Ron_Adam

Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error. I haven't tested
it on linux yet either. It could be something with my python
install.(?)


Here's the error I'm getting from the python command window.



C:\ron\rondev\pythonmods>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "pnames.py", line 28, in pnames
name = sys._getframe(n).f_code.co_name
ValueError: call stack is not deep enough


I fixed it, it now works in winpython and from the command line.

If anyones interested.

Ron
 
R

Ron_Adam

Fixed it so it now runs from the command line and from winpython as
well as idle in Python 2.4 on Windows Xp. I still don't know about
linux systems.

I decided on viewnames.py as the filename and viewit() as the calling
name.



#---start---

# viewnames.py
"""
A utility to print the value of variables for
debugging and instructional purposes.

To use:
from viewnames import viewit
viewit()

Insert it in the program where you want to examine names.
It will pause after it prints so that it will work in loops.

Author: Ronald Adam
"""

import sys
if __name__ is not '__main__':
import __main__

def readnames():
"""
Build a sequential name list and a dictionary of
objects and name references by groups.
"""
objdict = {} # Collect references to object.
namelist = [] # List of names and values by frame.
n = 2
name = None
while name not in ['runcode', 'RunScript', chr(63)]:
# Move up in the frames to gather name data.
# until the application global frame is reached.
name = sys._getframe(n).f_code.co_name
#print name
namelst = [name,[]]
namespace = sys._getframe(n).f_locals
keys = namespace.keys()
# Get all the names in this frame.
for k in keys:
try:
trash = objdict[id(namespace[k])][name]
except:
try:
objdict[id(namespace[k])][name]=[k]
except:
objdict[id(namespace[k])]={name:[k]}
else:
objdict[id(namespace[k])][name].append(k)
namelst[1].append((k,namespace[k],id(namespace[k])))
# Read any attributes if there is a dictionary.
attribs = None
try:
attribs = namespace[k].func_dict
except:
pass
if attribs:
for att in attribs:
attname = k+'.'+att
try:
trash = objdict[id(attribs[att])][attname]
except:
try:
objdict[id(attribs[att])][name]=[attname]
except:
objdict[id(attribs[att])]={name:[attname]}
else:

objdict[id(attribs[att])][name].append(attname)

namelst[1].append((attname,attribs[att],id(attribs[att])))
namelist.append(namelst)
n += 1
return objdict, namelist

def sortnocase(stringlist):
tupleList = [(x[0].lower(), x) for x in stringlist]
tupleList.sort()
return [x[1] for x in tupleList]

def printnames( objdict, namelist):
"""
Now print what we collected.
"""
namelist.reverse() # Reverse it so we have globals at the
top.
tab = 0
for gname, group in namelist:
# Print group name.
if gname == chr(63): # Idle uses this as name as
app-globals.
gname = 'globals'
if gname == namelist[-1:][0][0]:
gname = 'locals:'+gname # Indicate locals group.
print '%s[%s]'%(' '*tab, gname)
tab += 1

# Print group items.
# Sort group fist.
group = sortnocase(group)
for name, obj, objid in group:

# Print the varable name
print ' '*tab,name,'-->',

# Print object
# Remove & replace a lot of clutter as we print it.
# List other names pointing to mutable objects.
obj2 = obj # Make a copy to edit if needed.
if name == '__doc__':
if len(str(obj))>30:
obj2 = obj2.strip()
obj2 = '"'+obj2[:6]+' ... '+obj2[-6:]+'"'
#obj = '<docstring>'
if 'module' in str(obj): # These remove clutter
obj2 = '<module>' # More probably needs to be
if 'function' in str(obj): # done here.
obj2 = '<function>'

# Print the object
print obj2,

# Print the other names pointing to
# the object.
endofline = ''
# If object is immutable, don't print references.
if type(obj) not in [int, str, float, bool, tuple] \
and obj not in [True, False, None]:
for key in objdict[objid].keys():
grp = key
if key == chr(63):
grp = 'globals'

namegroup = objdict[objid][key]
n = 0
for nm in namegroup:
if nm != name:
if n>0:
endofline += ', '
if grp != gname:
endofline += grp+':'+nm
else:
endofline += nm
n += 1

if len(endofline)>0:
endofline = '<-- '+endofline
print endofline

def viewit():
""" Show current names """
objdict, namelist = readnames()
print
printnames( objdict, namelist)
print
raw_input('Press enter to continue.')


"""
A few nonsense test functions.
"""
def test1():
global g
t = g
t = [9]
test2.at1 = [True]
test2(t)

def test2(w):
a = glist
aaa = test2.at1
test2.at1[0] = True
a[0] = 'a changed'
w[0] = 'altered'
viewit()


if __name__ == '__main__':
# Make a few globals to see.
g = 45
h = g
glist = ['just a','list']

# Put an attribute on a function
# to find.
test2.at1 = 25

# Run test function.
test1()

#---end---
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top