Finding what methods a Python object has


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


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?

This question is tagged with python introspection

~ Asked on 2008-08-29 15:05:17

20 Answers


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 (now archived). Hopefully, that should provide some further detail!

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

getattr( is intolerant of pandas style python3.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):
        if callable(getattr(object, method_name)):
  processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
  for method in methodList:
        print(str(method.ljust(spacing)) + ' ' +
              processFunc(str(getattr(object, method).__doc__)[0:90]))
        print(method.ljust(spacing) + ' ' + ' getattr() failed')


~ Answered on 2008-08-29 15:09:05


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.

~ Answered on 2008-08-29 15:36:55


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

~ Answered on 2013-11-20 16:06:27


I believe that you want something like this:

a list of attributes from an object

The built-in function dir() can do this job.

Taken from help(dir) output on your Python shell:


dir([object]) -> list of strings

If called without an argument, return the names in the current scope.

Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it.

If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns:

  • for a module object: the module's attributes.
  • for a class object: its attributes, and recursively the attributes of its bases.
  • for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.

For example:

$ 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"
>>> type(a)
<class 'str'>
>>> 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']

~ Answered on 2016-05-26 14:58:48


To check if it has a particular method:


~ Answered on 2008-08-29 15:40:05


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:


to see the pydocs, method signature, etc.

Ahh... REPL.

~ Answered on 2008-08-29 15:47:04


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

~ Answered on 2015-01-29 17:10:18


Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:

[email protected]:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__(           s.__rmod__(          s.istitle(
s.__class__(         s.__rmul__(          s.isupper(
s.__contains__(      s.__setattr__(       s.join(
s.__delattr__(       s.__sizeof__(        s.ljust(
s.__dir__(           s.__str__(           s.lower(
s.__doc__            s.__subclasshook__(  s.lstrip(
s.__eq__(            s.capitalize(        s.maketrans(
s.__format__(        s.casefold(          s.partition(
s.__ge__(              s.replace(
s.__getattribute__(  s.count(             s.rfind(
s.__getitem__(       s.encode(            s.rindex(
s.__getnewargs__(    s.endswith(          s.rjust(
s.__gt__(            s.expandtabs(        s.rpartition(
s.__hash__(          s.find(              s.rsplit(
s.__init__(          s.format(            s.rstrip(
s.__iter__(          s.format_map(        s.split(
s.__le__(            s.index(             s.splitlines(
s.__len__(           s.isalnum(           s.startswith(
s.__lt__(            s.isalpha(           s.strip(
s.__mod__(           s.isdecimal(         s.swapcase(
s.__mul__(           s.isdigit(           s.title(
s.__ne__(            s.isidentifier(      s.translate(
s.__new__(           s.islower(           s.upper(
s.__reduce__(        s.isnumeric(         s.zfill(
s.__reduce_ex__(     s.isprintable(
s.__repr__(          s.isspace(

~ Answered on 2017-11-15 20:56:13


The simplest way to get a list of methods of any object is to use the help() command.


It will list out all the available/important methods associated with that object.

For example:


~ Answered on 2018-04-26 19:32:49


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 through __getattr__ and __getattribute__, making it possible to create method "at runtime"


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 non-existing methods in the object dictionary...

>>> o = MoreMethod()
>>> o.some_method(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)

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

~ Answered on 2014-12-09 14:02:06


import moduleName
for x in dir(moduleName):

This should work :)

~ Answered on 2019-11-22 04:10:49


Suppose we have a Python obj. Then to see all the methods it has, including those surrounded by __ (magic methods):


To see only methods available via infix (dot) notation, one would:

[m for m in dir(obj) if not m.startswith('__')]

~ Answered on 2020-12-07 17:38:27


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.

~ Answered on 2015-09-16 12:13:18


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

~ Answered on 2015-04-24 15:37:28


You can make use of dir() which is pre-defined in Python.

import module_name

You can also pass an object to dir() as


If the object is an object of a pre-defined class such as int, str, etc. it displays the methods in it (you may know those methods as built in functions). If that object is created for a user-defined class, it displays all the methods given in that class.

~ Answered on 2020-08-19 06:20:22


Take a list as an object

obj = []

list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))

You get:


~ Answered on 2018-01-16 15:34:59

0 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, you may be looking for:

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
# OUT: 'bar'

~ Answered on 2013-03-26 14:51:55


In order to search for a specific method in a whole module

for method in dir(module) :
  if "keyword_of_methode" in method :
   print(method, end="\n")

~ Answered on 2018-03-09 13:11:50


I have done the following function (get_object_functions), which receives an object (object_) as its argument, and returns a list (functions) containing all of the methods (including static and class methods) defined in the object's class:

def get_object_functions(object_):
    functions = [attr_name
                 for attr_name in dir(object_)
                 if str(type(getattr(object_,
                                     attr_name))) in ("<class 'function'>",
                                                      "<class 'method'>")]
    return functions

Well, it just checks if the string representation of the type of a class' attribute equals "<class 'function'>" or "<class 'method'>" and then includes that attribute in the functions list if that's True.


class Person:
    def __init__(self, name, age): = name
        self.age = age

    def introduce(self):
        print(f'My name is {}')

    def say_hi():

    def reproduce(cls, name):
        return cls(name, 0)

person = Person('Rafael', 27)


['__init__', 'introduce', 'reproduce', 'say_hi']

For a cleaner version of the code:

~ Answered on 2020-08-27 16:49:15


If you are, for instance, using shell plus you can use this instead:

>> MyObject??

that way, with the '??' just after your object, it'll show you all the attributes/methods the class has.

~ Answered on 2020-04-13 14:19:36

Most Viewed Questions: