473,385 Members | 1,312 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Anyone has a nice "view_var" procedure ?

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
11 1509
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

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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: dinesh prasad | last post by:
I'm trying to use a servlet to process a form, then send that data to an SQL server stored procedure. I'm using the WebLogic 8 App. server. I am able to retrieve database information, so I know my...
6
by: Martin Feuersteiner | last post by:
Dear Group I have found that table A had SELECT permissions for 'Public' but not table B. Giving 'Public' SELECT permissions on table B did the trick. HOWEVER, I don't want anyone to be able...
1
by: Neil | last post by:
Hello, I have a SQL Server 2000 database with an Access 97 front end. I want to run stored procedures, (not nessessarily ones which return records either - action type queries for adding new...
15
by: Steve | last post by:
I am trying to develop a stored procedure for an existing application that has data stored in numerous tables, each with the same set of columns. The main columns are Time and Value. There are...
9
by: fniles | last post by:
I am using VB.NET 2003 and SQL2000 database. I have a stored procedure called "INSERT_INTO_MYTABLE" that accepts 1 parameter (varchar(10)) and returns the identity column value from that table....
13
by: Neil | last post by:
Can I get the name of a procedure from within the procedure? In my error handler, I write the error to an error table. I'd like to write the name of the procedure that's writing the error. But,...
20
by: billmaclean1 | last post by:
I need to write a stored procedure that selects from a table and returns the result set. I don't always know the TableSchema that I need to use when qualifying the table at run-time Example:...
3
by: sheldonlg | last post by:
I think this capability is lacking in php. Suppose there is a group of checkboxes all named "procedure". Doing a $_POST returns all the ones that are checked and not the ones that are not...
2
by: IuliaS | last post by:
Hello everyone! I want to create a stored procedure, so I can more easily, and transparent retrieve data from db2. Long story short: when a user wants to put some data in the DB, he also creates...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.