How to Get a Complete List of Object's Methods and Attributes

How to get a complete list of object's methods and attributes?

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

How do I get list of methods in a Python class?

An example (listing the methods of the optparse.OptionParser class):

>>> from optparse import OptionParser
>>> import inspect
#python2
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
# python3
>>> inspect.getmembers(OptionParser, predicate=inspect.isfunction)
...

Notice that getmembers returns a list of 2-tuples. The first item is the name of the member, the second item is the value.

You can also pass an instance to getmembers:

>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...

Get all object attributes in Python?

Use the built-in function dir().

Get complete list of all possible Class Attributes

dir() is basically a convenience method, it is not supposed to return everything, what it basically does is that it recursively returns everything found in the dictionary of a class and its bases.

PyPy's implementation of dir() is quite easy to understand:

def dir(*args):
...
elif isinstance(obj, (types.TypeType, types.ClassType)):
# Don't look at __class__, as metaclass methods would be confusing.
return sorted(_classdir(obj))
...

def _classdir(klass):
"""Return a set of the accessible attributes of class/type klass.

This includes all attributes of klass and all of the base classes
recursively.
"""
names = set()
ns = getattr(klass, '__dict__', None)
if ns is not None:
names.update(ns)
bases = getattr(klass, '__bases__', None)
if bases is not None:
# Note that since we are only interested in the keys, the order
# we merge classes is unimportant
for base in bases:
names.update(_classdir(base))
return names

As each class basically inherits from object you will see some dunder methods included because they are actually part of object's dictionary:

>>> class A(object):
pass
...
>>> set(dir(A)) == set(list(object.__dict__) + list(A.__dict__))
True

Now what about __bases__ and other missing items?

First of all object itself is an instance of something, well it's bit of a mess actually:

>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
>>> issubclass(type, object)
True
>>> issubclass(object, type)
False
>>> type.mro(object)
[<type 'object'>]
>>> type.mro(type)
[<type 'type'>, <type 'object'>]

So, all of the attributes like __bases__, __ge__ etc are actually part of type:

>>> list(type.__dict__)
['__module__', '__abstractmethods__', '__getattribute__', '__weakrefoffset__', '__dict__', '__lt__', '__init__', '__setattr__', '__subclasses__', '__new__', '__base__', '__mro__', 'mro', '__dictoffset__', '__call__', '__itemsize__', '__ne__', '__instancecheck__', '__subclasscheck__', '__gt__', '__name__', '__eq__', '__basicsize__', '__bases__', '__flags__', '__doc__', '__delattr__', '__le__', '__repr__', '__hash__', '__ge__']

Hence when we do A.__bases__ we are actually looking up a descriptor on type of A, i.e type:

>>> A.__bases__
(<type 'object'>,)
>>> type(A).__dict__['__bases__'].__get__(A, type)
(<type 'object'>,)

So, as A is an instance of type these methods are not part of its own dictionary but its type's dictionary.

>> class A(object):
... spam = 'eggs'
...
>>> a = A()
>>> a.foo = 100
>>> a.bar = 200
>>> a.__dict__
{'foo': 100, 'bar': 200}
>>> A.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None, 'spam': 'eggs'})

As, type is a subclass of object, the dir() call on type will contain some items from object:

>>> set(dir(type)) - set(type.__dict__)
set(['__reduce_ex__', '__str__', '__format__', '__reduce__', '__class__', '__subclasshook__', '__sizeof__'])

Finding what methods a Python object has

For many objects, you can use this code, replacing 'object' with the object you're interested in:

object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]

I discovered it at diveintopython.net (now archived), that should provide some further details!

If you get an AttributeError, you can use this instead:

getattr() is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.

import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
methodList = []
for method_name in dir(object):
try:
if callable(getattr(object, method_name)):
methodList.append(str(method_name))
except Exception:
methodList.append(str(method_name))
processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
for method in methodList:
try:
print(str(method.ljust(spacing)) + ' ' +
processFunc(str(getattr(object, method).__doc__)[0:90]))
except Exception:
print(method.ljust(spacing) + ' ' + ' getattr() failed')

get_methods(df['foo'])

Is there a function in Python to list the attributes and methods of a particular object?

You want to look at the dir() function:

>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']

li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.


Edit in response to comment:

No this will show all inherited methods as well. Consider this example:

test.py:

class Foo:
def foo(): pass

class Bar(Foo):
def bar(): pass

Python interpreter:

>>> from test import Foo, Bar
>>> dir(Foo)
['__doc__', '__module__', 'foo']
>>> dir(Bar)
['__doc__', '__module__', 'bar', 'foo']

You should note that Python's documentation states:

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
. For
example, metaclass attributes are not
in the result list when the argument
is a class.

Therefore it's not safe to use in your code. Use vars() instead. Vars() doesn't include information about the superclasses, you'd have to collect them yourself.


If you're using dir() to find information in an interactive interpreter, consider the use of help().

How to list all fields of a class (and no methods)?

You can get it via the __dict__ attribute, or the built-in vars function, which is just a shortcut:

>>> class A(object):
... foobar = 42
... def __init__(self):
... self.foo = 'baz'
... self.bar = 3
... def method(self, arg):
... return True
...
>>> a = A()
>>> a.__dict__
{'foo': 'baz', 'bar': 3}
>>> vars(a)
{'foo': 'baz', 'bar': 3}

There's only attributes of the object. Methods and class attributes aren't present.

How to list all functions in a module?

Use the inspect module:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

Also see the pydoc module, the help() function in the interactive interpreter and the pydoc command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.



Related Topics



Leave a reply



Submit