Anyone has a nice "view_var" procedure ?

Neil Cerutti horpner at yahoo.com
Tue Jan 16 13:29:51 CET 2007


On 2007-01-15, Gabriel Genellina <gagsl-py at yahoo.com.ar> wrote:
> 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.
>
> 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:

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



More information about the Python-list mailing list