Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows two quick-and-clean :) utility functions for introspection of Python objects. They are meant to be used while working interactively in the reular Python shell or in the IPython shell. Both of them display attributes of any given object passed as the argument. The first function displays all attributes. The second function only displays atttributes that do not begin and end with a double underscore, so as to filter out "dunder" methods a.k.a. "special" methods - like __len__, __str__, __repr__, etc. The first function - oa(o) , where o is some object - does the same as dir(o), but is useful - in IPython - because, dir(o) output will scroll off the screen if the output is long, since it prints the attributes vertically, one per line, while oa(o) prints them horizontally, so has less chance of the output scrolling off, and the output also occupies fewer lines on the screen, so is easier to scan quickly. The second function - oar(o) - is like oa(o), but filters out attribute names that begin and end with a dunder. So it is useful in both IPython and Python.

More information and outputs here:

https://jugad2.blogspot.in/2017/01/two-simple-python-object-introspection.html

Python, 59 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def oa(o):
    for at in dir(o):
        print at,

'''
Sample calls and output for oa() below:

# object attributes of a dict:
oa({})
__class__ __cmp__ __contains__ __delattr__ __delitem__ __doc__ __eq__ __format__
__ge__ __getattribute__ __getitem__ __gt__ __hash__ __init__ __iter__ __le__ __len__ 
__lt__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __setitem__ 
__sizeof__ __str__ __subclasshook__ clear copy fromkeys get has_key items
iteritems iterkeys itervalues keys pop popitem setdefault update values viewitems 
viewkeys viewvalues

# object attributes of a list:
oa([])
__add__ __class__ __contains__ __delattr__ __delitem__ __delslice__ __doc__ __eq__ 
__format__ __ge__ __getattribute__ __getitem__ __getslice__ __gt__ __hash__ __iadd__ 
__imul__ __init__ __iter__ __le__ __len__ __lt__ __mul__ __ne__ __new__
__reduce__ __reduce_ex__ __repr__ __reversed__ __rmul__ __setattr__ __setitem__
__setslice__ __sizeof__ __str__ __subclasshook__ append count extend index insert 
pop remove reverse sort

# object attributes of an int:
oa(1)
__abs__ __add__ __and__ __class__ __cmp__ __coerce__ __delattr__ __div__ __divmod__ 
__doc__ __float__ __floordiv__ __format__ __getattribute__ __getnewargs__ __hash__ 
__hex__ __index__ __init__ __int__ __invert__ __long__ __lshift__ __mod__
__mul__ __neg__ __new__ __nonzero__ __oct__ __or__ __pos__ __pow__ __radd__ __rand__ 
__rdiv__ __rdivmod__ __reduce__ __reduce_ex__ __repr__ __rfloordiv__ __rlshift__ 
__rmod__ __rmul__ __ror__ __rpow__ __rrshift__ __rshift__ __rsub__ __rtruediv__ 
__rxor__ __setattr__ __sizeof__ __str__ __sub__ __subclasshook__ __truediv__ 
__trunc__ __xor__ bit_length conjugate denominator imag numerator real
'''

def oar(o):
    for at in dir(o):
        if not at.startswith('__') and not at.endswith('__'):
            print at,

'''
# regular (meaning non-dunder) object attributes of a dict:
oar({})
clear copy fromkeys get has_key items iteritems iterkeys itervalues keys pop popitem 
setdefault update values viewitems viewkeys viewvalues

# regular object attributes of an int:
oar(1)
bit_length conjugate denominator imag numerator real

# regular object attributes of a string:
oar('')
_formatter_field_name_split _formatter_parser capitalize center count decode encode 
endswith expandtabs find format index isalnum isalpha isdigit islower isspace 
istitle isupper join ljust lower lstrip partition replace rfind rindex rjust rpartition 
rsplit rstrip split splitlines startswith strip swapcase title translate upper zfil
'''

More information and outputs here:

https://jugad2.blogspot.in/2017/01/two-simple-python-object-introspection.html

A user may want to use these recipes because they provide a quick way to see the attributes of an object. They serve a somewhat different, though partially overlapping purpose, than the recipe here:

https://code.activestate.com/recipes/580705-get-names-and-types-of-all-attributes-of-a-python-/?in=user-4173351

which shows the names and types of all attributes of a Python module. The latter recipe is more useful when you are exploring a module for the first time(s), to get familiar with what attributes (whether data members or functions or methods) it contains, while the former two (mentioned in this recipe) are more useful to quickly get a reminder of what the attributes (e.g. methods) of a Python object (which is often a class instance) are, though you knew them from before, so that you can decide which, if any, of them is suitable for some work you want to do. E.g. you may have read the dir(o) output for some object o of some type, earlier, but since there are many types, you may not remember it unless you use it regularly, though you did understand how to use its methods earlier - so now if you use oa(o) or oar(o), you get reminded of what the methods are in that object, and since you know what each is for, you can quickly decide which method(s) can be used for your current programming task.