Anyone has a nice "view_var" procedure ?

S

Stef Mientki

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
 
G

Gabriel Genellina

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.

py> import csv
py> x = csv.DictReader('') # a bogus object
py> x
<csv.DictReader instance at 0x00BC79B8>
py> dir(x)
['__doc__', '__init__', '__iter__', '__module__', 'fieldnames',
'next', 'reader'
, 'restkey', 'restval']
py> vars(x)
{'restkey': None, 'restval': None, 'fieldnames': None, 'reader':
<_csv.reader ob
ject at 0x00BC98B8>}
py> from pprint import pprint
py> pprint(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
 
A

Adam

Stef said:
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(aVar[0])
type(aVar[1])
type(aVar[2])
if type(aVar[1]) == int:
print "test"

test
#-----------------End Code-------------------------------


There are also function like len(). Usage:
#-------------Python Code-----------------------------
4
#-----------------End Code-------------------------------

Hope this helps.
Adam
 
L

Larry Bates

Stef said:
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
 
N

Neil Cerutti

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.

py> import csv
py> x = csv.DictReader('') # a bogus object
py> x
<csv.DictReader instance at 0x00BC79B8>
py> dir(x)
['__doc__', '__init__', '__iter__', '__module__', 'fieldnames',
'next', 'reader'
, 'restkey', 'restval']
py> vars(x)
{'restkey': None, 'restval': None, 'fieldnames': None, 'reader':
<_csv.reader ob
ject at 0x00BC98B8>}
py> from pprint import pprint
py> pprint(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:
['__copy__',
'__deepcopy__',
'end',
'expand',
'group',
'groupdict',
'groups',
'span',
'start']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. ;)
 
D

Duncan Booth

Neil Cerutti said:
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__:
def __getattribute__(self, name):
if name.startswith('weird'):
return 42

[]

Any objects which are actually implemented as C extensions are quite likely
to have attributes that dir() cannot see.
 
S

Stef Mientki

Adam said:
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_unknown =
0,0,0,0,0,0,0
for i in range(len(V)):
if type(V) == int: N_int += 1
elif type(V) == float: N_float += 1
elif type(V) == complex: N_complex += 1
elif type(V) == list: N_list += 1
elif type(V) == tuple: N_tuple += 1
elif type(V) == 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)
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 )
 
G

Gabriel Genellina

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_unknown =
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) == int: N_int += 1
elif type(V) == 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
 
S

Stef Mientki

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_unknown =
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
 
G

Gabriel Genellina

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
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top