By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,001 Members | 1,176 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,001 IT Pros & Developers. It's quick & easy.

Anyone has a nice "view_var" procedure ?

P: n/a
hello,

Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.

Probably it's not so difficult,
but I don't see how to distinguish for example between a string and an
array. An array has a shape, a string not etc.
thanks,
Stef Mientki
Jan 15 '07 #1
Share this Question
Share on Google+
11 Replies


P: n/a
At Monday 15/1/2007 17:45, Stef Mientki wrote:
>Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.
You can try dir(x), vars(x). If you want a "nice print", see the pprint module.

pyimport csv
pyx = csv.DictReader('') # a bogus object
pyx
<csv.DictReader instance at 0x00BC79B8>
pydir(x)
['__doc__', '__init__', '__iter__', '__module__', 'fieldnames',
'next', 'reader'
, 'restkey', 'restval']
pyvars(x)
{'restkey': None, 'restval': None, 'fieldnames': None, 'reader':
<_csv.reader ob
ject at 0x00BC98B8>}
pyfrom pprint import pprint
pypprint(vars(x))
{'fieldnames': None,
'reader': <_csv.reader object at 0x00BC98B8>,
'restkey': None,
'restval': None}
py>
>Probably it's not so difficult,
but I don't see how to distinguish for example between a string and an
array. An array has a shape, a string not etc.
Yes, strings share a lot of functionality with other sequence types:
[], len, in, etc. You can test if an object is a string using
isinstance(obj, str). If you want to include unicode objects too, use
isinstance(obj, basestring).
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 15 '07 #2

P: n/a

Stef Mientki wrote:
hello,

Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.

Probably it's not so difficult,
but I don't see how to distinguish for example between a string and an
array. An array has a shape, a string not etc.
thanks,
Stef Mientki
I am also a newbie so if this is not what you want I can't give much
more as of yet.

You can use type() to check what a Variable is. Usage:
#-------------Python Code-----------------------------
>>aVar = ["zero", 1, float(2)]
type(aVar)
<type 'list'>
>>type(aVar[0])
<type 'str'>
>>type(aVar[1])
<type 'int'>
>>type(aVar[2])
<type 'float'>
>>if type(aVar[1]) == int:
print "test"

test
#-----------------End Code-------------------------------
There are also function like len(). Usage:
#-------------Python Code-----------------------------
>>len(aVar)
3
>>len(aVar[0])
4
#-----------------End Code-------------------------------

Hope this helps.
Adam

Jan 15 '07 #3

P: n/a
Stef Mientki wrote:
hello,

Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.

Probably it's not so difficult,
but I don't see how to distinguish for example between a string and an
array. An array has a shape, a string not etc.
thanks,
Stef Mientki
Others have given some suggestions, but I thought I'd put in my
thoughts also. When I first started using Python I was looking for
exactly what you describe. After using a while, you begin to understand
that the objects in Python can be so complex (lists of dictionaries that
contain lists and other dictionaries, lists of class instances that can
contain other class instances, that can contain...., you get the picture).
You have to begin to think about navigating through this by using dir(),
vars() and pprint.pprint(). Unlike older programming languages there is
no limit to how you can mix/match values within an object.

Also in standard Python lists (arrays?) don't have shape (there are add
on modules that give you this type of feature). Everything is a
collection of objects.

class foo:
def __init__(self):
self.x=1
self.y=2

l=[[1,2,3], 'test', 6, 3.14159, {'a':1, 'b':2}, foo()]

a list with:
a list as first element
a string as the second element
an integer as the third element
a float as the third element
a dictionary as the fourth element
a class instance as the fifth element

The tutorial is a good place to start if you haven't already looked at
it.

-Larry Bates
Jan 16 '07 #4

P: n/a
On 2007-01-15, Gabriel Genellina <ga******@yahoo.com.arwrote:
At Monday 15/1/2007 17:45, Stef Mientki wrote:
>>Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.

You can try dir(x), vars(x). If you want a "nice print", see
the pprint module.

pyimport csv
pyx = csv.DictReader('') # a bogus object
pyx
<csv.DictReader instance at 0x00BC79B8>
pydir(x)
['__doc__', '__init__', '__iter__', '__module__', 'fieldnames',
'next', 'reader'
, 'restkey', 'restval']
pyvars(x)
{'restkey': None, 'restval': None, 'fieldnames': None, 'reader':
<_csv.reader ob
ject at 0x00BC98B8>}
pyfrom pprint import pprint
pypprint(vars(x))
{'fieldnames': None,
'reader': <_csv.reader object at 0x00BC98B8>,
'restkey': None,
'restval': None}
py>
It's an unfortunately limited sort of introspection. To rehash a
recent experience:
>>import re
import pprint
r = re.match("(x+)|(y+)", "xxx")
pprint.pprint(dir(r))
['__copy__',
'__deepcopy__',
'end',
'expand',
'group',
'groupdict',
'groups',
'span',
'start']
>>r.lastindex
1

The documentation is deliberately vague:

dir( [object])

[...] The list is not necessarily
complete. If the object is a module object, the list contains
the names of the module's attributes. If the object is a type
or class object, the list contains the names of its attributes,
and recursively of the attributes of its bases. Otherwise, the
list contains the object's attributes' names, the names of its
class's attributes, and recursively of the attributes of its
class's base classes. The resulting list is sorted
alphabetically. [...]

It's unclear to me what attributes an object could have that
aren't included in the above list.

Note: Because dir() is supplied primarily as a convenience for
use at an interactive prompt, it tries to supply an interesting
set of names more than it tries to supply a rigorously or
consistently defined set of names, and its detailed behavior
may change across releases.

In other words, dir is just for fun, like monkey bars. ;)

--
Neil Cerutti
The eighth-graders will be presenting Shakespeare's Hamlet in the church
basement on Friday at 7 p.m. The congregation is invited to attend this
tragedy. --Church Bulletin Blooper
Jan 16 '07 #5

P: n/a
Neil Cerutti <ho*****@yahoo.comwrote:
dir( [object])

[...] The list is not necessarily
complete. If the object is a module object, the list contains
the names of the module's attributes. If the object is a type
or class object, the list contains the names of its attributes,
and recursively of the attributes of its bases. Otherwise, the
list contains the object's attributes' names, the names of its
class's attributes, and recursively of the attributes of its
class's base classes. The resulting list is sorted
alphabetically. [...]

It's unclear to me what attributes an object could have that
aren't included in the above list.
For a start the potentially infinite list of attributes handled by
__getattr__ or __getattribute__:
>>class C(object):
def __getattribute__(self, name):
if name.startswith('weird'):
return 42

>>c = C()
c.weirdattribute
42
>>dir(c)
[]

Any objects which are actually implemented as C extensions are quite likely
to have attributes that dir() cannot see.
Jan 16 '07 #6

P: n/a
Adam wrote:
Stef Mientki wrote:
>hello,

Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.

Probably it's not so difficult,
but I don't see how to distinguish for example between a string and an
array. An array has a shape, a string not etc.
thanks,
Stef Mientki

I am also a newbie so if this is not what you want I can't give much
more as of yet.
Ok, here's my current solution,
probably not very Pythonian, (so suggestions are welcome)
but it works.
(Too bad I can get the name of the var into a function ;-)

cheers,
Stef Mientki

from scipy import *
#
################################################## ###########################
def prn ( V ):
# print a single row of an array
def prn_array_row ( R, row ):
if len(R) < 4: print ' Row', row, ':', R
else:
print ' Row', row, ': [', R[0],R[1], '...', R[-2], R[-1], ']'

# print a single element of a list
def prn_list_element ( E ):
if type(E) == int: return ' ' + str(E)
elif type(E) == float: return ' ' + str(E)
elif type(E) == complex: return ' ' + str(E)
elif type(E) == list: return ' [..]'
elif type(E) == tuple: return ' (..)'
elif type(E) == array: return ' ([..])'
else: return ' ??'

print ''
if type(V) == int:
print 'int32 =', V

elif type(V) == float:
print 'float64 =', V

elif type(V) == complex:
print 'complex64 =', V

# LIST
elif (type(V) == list) | (type(V) == tuple):
# count the occurances of the different types
N_int,N_float,N_complex,N_list,N_tuple,N_array,N_u nknown =
0,0,0,0,0,0,0
for i in range(len(V)):
if type(V[i]) == int: N_int += 1
elif type(V[i]) == float: N_float += 1
elif type(V[i]) == complex: N_complex += 1
elif type(V[i]) == list: N_list += 1
elif type(V[i]) == tuple: N_tuple += 1
elif type(V[i]) == ndarray: N_array += 1
else: N_unknown += 1

# print the occurances of the different types
# and count the number of types that can easily be displayed
if type(V)==list: line = 'list:'
else: line = 'tuple:'
N = 0
if N_int 0: line = line + ' N_Int=' + str(N_int) ; N
+= 1
if N_float 0: line = line + ' N_Float=' + str(N_float) ; N
+= 1
if N_complex 0: line = line + ' N_Complex=' + str(N_complex) ; N
+= 1
if N_list 0: line = line + ' N_List=' + str(N_list) ; N
+= 1
if N_tuple 0: line = line + ' N_Tuple=' + str(N_tuple) ; N
+= 1
if N_array 0: line = line + ' N_Array=' + str(N_array) ; N
+= 1
if N_unknown 0: line = line + ' N_Unknown=' + str(N_unknown) ; N
+= 1
if N == 1: line += ' == Homogeneous =='
print line

# check if all elements have the same type

if len(V) < 4:
line = ''
for i in range(len(V)): line += prn_list_element (V[i])
print line
else:
print prn_list_element (V[0]),\
prn_list_element (V[1]),\
' .....',\
prn_list_element (V[-2]),\
prn_list_element (V[-1])

# ARRAY
elif type(V) == ndarray:
print 'Array', V.shape, V.dtype.name
if V.ndim == 1:
prn_array_row ( V, 0 )
elif V.ndim == 2:
if V.shape[1] < 4:
for i in range(V.ndim): prn_array_row ( V[i,:], i )
else:
prn_array_row ( V[0,:], 0 )
prn_array_row ( V[1,:], 1 )
print ' ......'
prn_array_row ( V[-2,:], V.shape[1]-2 )
prn_array_row ( V[-1,:], V.shape[1]-1 )
# MAIN TEST PROGRAM
################################################## ########
V1 = 3
L1 = [ 11, 12, 33 ]
L2 = [ 11, 12, ['aap', 34] ]
T1 = ( 11, 12, ('aap', 34) )
T2 = ( 11, ('aap', 34), 5,5,5,5,5,5,8 )
A1 = array ( [1,2,7] )
A2 = array ( [ [1,2,4,4,4,4,4,8], [4,5,5,5,5,5,5,2] ] )
A3 = zeros ((10,10))
prn ( V1 )
prn ( L1 )
prn ( A1 )
prn ( A2 )
prn ( A3 )
prn ( L2 )
prn ( T1 )
prn ( T2 )
Jan 16 '07 #7

P: n/a
At Tuesday 16/1/2007 20:13, Stef Mientki wrote:
>Ok, here's my current solution,
probably not very Pythonian, (so suggestions are welcome)
but it works.
It appears that you're a number crunching guy - you absolutely ignore
all types except numeric ones! :)
>(Too bad I can get the name of the var into a function ;-)
I don't understand this, but if you are saying that you can't get the
name of the variable you're showing - just pass the name to the
function: def pm(V, name)
# count the occurances of the different types
N_int,N_float,N_complex,N_list,N_tuple,N_array,N_u nknown =
0,0,0,0,0,0,0
Ouch, seven counters... your guts should be saying that this is
candidate for a more structured type... what about a dictionary
indexed by the element type?

count = {}
for i in range(len(V)):
You're going to iterate along all the items in V, not along its indices...
if type(V[i]) == int: N_int += 1
elif type(V[i]) == float: N_float += 1
elif ...
Using a dict:

for item in V:
t = type(item)
try: count[t] = count[t]+1
except IndexError: count[t] = 1

(That is: if the type is found in the dictionary, increment the
count; if not, this is the first time: set the count to 1)
# print the occurances of the different types
# and count the number of types that can easily be displayed
if type(V)==list: line = 'list:'
else: line = 'tuple:'
N = 0
if N_int 0: line = line + ' N_Int=' + str(N_int) ; N
+= 1
if N_float 0: line = line + ' N_Float=' + str(N_float) ; N
+= 1
We'll replace all of this with:

for key,value in count:
line += ' %s=%d' % (key, value)
if N == 1: line += ' == Homogeneous =='
if len(count)==1: line += ' == Homogeneous =='
print line

--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 17 '07 #8

P: n/a
hi Gabriel,
It appears that you're a number crunching guy - you absolutely ignore
all types except numeric ones! :)
Is there anything else than numbers ? ;-)
But indeed I forgot the else statement, which should look like this:
else:
line = 'UNKNOWN: ' + type(V)
print line
line = ' ' + V.__repr__()
# do something to prevent too long output sequences
print line
>
> # count the occurances of the different types
N_int,N_float,N_complex,N_list,N_tuple,N_array,N_u nknown =
0,0,0,0,0,0,0

Ouch, seven counters... your guts should be saying that this is
candidate for a more structured type... what about a dictionary indexed
by the element type?
Using a dict:

for item in V:
t = type(item)
try: count[t] = count[t]+1
except IndexError: count[t] = 1
Thanks very much, that's almost perfect, I only had to change IndexError into KeyError.
>

We'll replace all of this with:

for key,value in count:
line += ' %s=%d' % (key, value)
I didn't succeed to use value as a enumerator, and I had to typecast key into a string (and skipping
some redundant information, but then it works great, thanks !!
here the complete listing:
count = {}
for item in V:
t = type(item)
try: count[t] += 1
except KeyError: count[t] = 1
if type(V)==list: line = 'list:'
else: line = 'tuple:'
for key in count: line += ' %s=%d' %('N_'+str(key)[7:-2],count[key])
print line

cheers,
Stef Mientki
Jan 17 '07 #9

P: n/a
At Wednesday 17/1/2007 19:46, Stef Mientki wrote:
for key,value in count:
line += ' %s=%d' % (key, value)
I didn't succeed to use value as a enumerator, and I had to typecast
key into a string (and skipping
some redundant information, but then it works great, thanks !!
Ouch, my fault! I didn't test it when I wrote it :(
>here the complete listing:
count = {}
for item in V:
t = type(item)
try: count[t] += 1
except KeyError: count[t] = 1
if type(V)==list: line = 'list:'
else: line = 'tuple:'
for key in count: line += ' %s=%d' %('N_'+str(key)[7:-2],count[key])
print line
str(key)[7:-2] =key.__name__

Nice to see you built a useful tool! It's a great way to learn a language.
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 17 '07 #10

P: n/a
thanks Gabriel
str(key)[7:-2] =key.__name__
I didn't know that one
Nice to see you built a useful tool! It's a great way to learn a language.
Yes, and this group is helping me a whole lot, thanks !

cheers,
Stef Mientki

Jan 18 '07 #11

P: n/a
At Thursday 18/1/2007 19:24, Stef Mientki wrote:
str(key)[7:-2] =key.__name__
I didn't know that one
It's here: http://docs.python.org/lib/specialattrs.html
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 19 '07 #12

This discussion thread is closed

Replies have been disabled for this discussion.