Finding what methods a Python object has

0 votes
asked Aug 29, 2008 by thomas-l%c3%b6tzer

Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?

Or,

if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?

10 Answers

0 votes
answered Aug 29, 2008 by ljs

It appears you can use this code, replacing 'object' with the object you're interested in:-

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

I discovered it at this site, hopefully that should provide some further detail!

0 votes
answered Aug 29, 2008 by bill-the-lizard

You can use the built in dir() function to get a list of all the attributes a module has. Try this at the command line to see how it works.

>>> import moduleName
>>> dir(moduleName)

Also, you can use the hasattr(module_name, "attr_name") function to find out if a module has a specific attribute.

See the Guide to Python introspection for more information.

0 votes
answered Aug 29, 2008 by jmanning2k

On top of the more direct answers, I'd be remiss if I didn't mention iPython. Hit 'tab' to see the available methods, with autocompletion.

And once you've found a method, try:

help(object.method) 

to see the pydocs, method signature, etc.

Ahh... REPL.

0 votes
answered Aug 20, 2013 by pawan-kumar

The simplest method is to use dir(objectname). It will display all the methods available for that object. Cool trick.

0 votes
answered Aug 26, 2013 by bruno-bronosky

...is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called

While "Easier to ask for forgiveness than permission" is certainly the Pythonic way, what you are looking for maybe:

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
    d.get('foo')
# OUT: 'bar'
0 votes
answered Aug 9, 2014 by cld

The problem with all methods indicated here is that you CAN'T be sure that a method doesn't exist.

In Python you can intercept the dot calling thru __getattr__ and __getattribute__, making it possible to create method "at runtime"

Exemple:

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2

If you execute it, you can call method non existing in the object dictionary...

>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10

And it's why you use the Easier to ask for forgiveness than permission paradigms in Python.

0 votes
answered Aug 16, 2015 by aver

There is no reliable way to list all object's methods. dir(object) is usually useful, but in some cases it may not list all methods. According to dir() documentation: "With an argument, attempt to return a list of valid attributes for that object."

Checking that method exists can be done by callable(getattr(object, method)) as already mentioned there.

0 votes
answered Aug 24, 2015 by james-womack

One can create a getAttrs function that will return an object's callable property names

def getAttrs(object):
  return filter(lambda m: callable(getattr(object, m)), dir(object))

print getAttrs('Foo bar'.split(' '))

That'd return

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__getslice__', '__gt__', '__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']
0 votes
answered Aug 29, 2015 by paulmelnikow

If you specifically want methods, you should use inspect.ismethod.

For method names:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]

For the methods themselves:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]

Sometimes inspect.isroutine can be useful too (for built-ins, C extensions, Cython without the "binding" compiler directive).

0 votes
answered Aug 26, 2016 by ivanleoncz

I believe that what you want is something like this:

a list of attributes/methods of an object

IMHO, dir() built-in can do this job for you.

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> a = "I am a string"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_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', 'zfill']

As I was checking your issue, I decided to make a script in order to better format and demonstrate the output of dir().

Here goes:

list_objects_methods.py

#!/usr/bin/python
OBJ = "I am a string."
COUNT = 0

for method in dir(OBJ):
    print "| {0: <20}".format(method),
    COUNT += 1
    if COUNT == 4:
        COUNT = 0
        print

Hope that I have contributed :). Regards!

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...