667

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 checking if an error occurs when the method is called?

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Thomas Lötzer
  • 24,832
  • 16
  • 69
  • 55

22 Answers22

743

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'])
bad_coder
  • 11,289
  • 20
  • 44
  • 72
ljs
  • 37,275
  • 36
  • 106
  • 124
  • 5
    It's a list comprehension, returning a list of methods where method is an item in the list returned by dir(object), and where each method is added to the list only if getattr(object,method) returns a callable. – Mnebuerquo Sep 13 '14 at 01:02
  • 16
    @marsh To print the methods: `print [method for method in dir(object) if callable(getattr(object, method))]`. – Orienteerix Oct 29 '15 at 10:51
  • 1
    I'm getting an `AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'` when I try to run this. See details at https://stackoverflow.com/q/54713287/9677043. – Karl Baker Feb 15 '19 at 16:26
  • To exclude dunder methods: `[ m for m in dir(object) if not m.startswith('__')]` – John Nov 15 '19 at 05:31
  • Other way using filter: `print(list(filter(lambda x: x[0] != '_' and callable(getattr(obj, x)), dir(obj))))` – Paulo Buchsbaum Feb 06 '20 at 20:13
  • Though such things are not common, this will return callable instance attributes that are not methods. A method results from calling a *class* attribute from an instance. Also, `dir` is not a reliable way to get *all* attributes of an object; most significantly, a class can define what `dir` returns by overriding `__dir__`. – chepner Jan 28 '21 at 12:38
360

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 Python introspection for more information.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
152

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

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Pawan Kumar
  • 2,132
  • 2
  • 16
  • 10
  • 5
    It also displays the attributes of the object, so if you want to specifically find methods, it will not work. – eric Dec 09 '17 at 18:05
  • Yes. Agreed. But, I am not aware of any other technique to only get the list of methods. Maybe the best idea is to get the list of both attributes and methods and then use to further filter it out? – Pawan Kumar Dec 10 '17 at 01:30
  • 1
    @neuronet, I'm trying to run the accepted answer but getting an `AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'`. Any ideas? See deets at https://stackoverflow.com/q/54713287/9677043. +1 to @Pawan Kumar b/c the answer works, and to @ljs for the promise of a filtered list of just the methods. – Karl Baker Feb 15 '19 at 16:37
40

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

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']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
34

To check if it has a particular method:

hasattr(object,"method")
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 15
    since the OP is looking for a method and not just and attribute, I think you want to go a step further with: `if hasattr(obj,method) and callable(getattr(obj,method)):` – Bruno Bronosky Mar 26 '13 at 14:33
27

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jmanning2k
  • 9,297
  • 4
  • 31
  • 23
27

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

help(object)

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

For example:

help(str)
Joshua Goldberg
  • 5,059
  • 2
  • 34
  • 39
Paritosh Vyas
  • 279
  • 3
  • 4
23

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

print(dir(obj))

To exclude magic builtins one would do:

[m for m in dir(obj) if not m.startswith('__')]
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
20

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 _
  • 10,524
  • 11
  • 77
  • 109
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
15

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:

user@note:~$ 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.center(            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(
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Valery Ramusik
  • 1,473
  • 18
  • 19
  • 1
    While we're talking about workarounds like this, I'll add that you can also run `ipython`, start typing the object and press `tab` and it'll work as well. No readline settings needed – Max Coplan Jul 29 '19 at 18:21
  • 1
    @MaxCoplan I've added the workaround in code for cases where tab-completion is not enabled by default – Valery Ramusik Jul 30 '19 at 12:30
10

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"

Example:

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cld
  • 461
  • 3
  • 7
4

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.

aver
  • 109
  • 1
  • 4
3
import moduleName
for x in dir(moduleName):
    print(x)

This should work :)

Georgy
  • 12,464
  • 7
  • 65
  • 73
The Mob
  • 391
  • 3
  • 10
2

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.


Demo

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

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

    @staticmethod
    def say_hi():
        print('hi')

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


person = Person('Rafael', 27)
print(get_object_functions(person))

Output

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

For a cleaner version of the code: https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
revliscano
  • 2,227
  • 2
  • 12
  • 21
1

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

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
    d.get('foo')
# OUT: 'bar'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149
1

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']
james_womack
  • 10,028
  • 6
  • 55
  • 74
1

Take a list as an object

obj = []

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

You get:

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
Mahdi Ghelichi
  • 1,090
  • 14
  • 23
0

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")
Simon PII
  • 441
  • 3
  • 8
0

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.

Nick Cuevas
  • 1,474
  • 15
  • 10
0

Most of the time, I want to see the user-defined methods and I don't want to see the built-in attributes that start with '__', if you want that you can use the following code:

object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name] 

For example, for this class:

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

Above code will print: ['print_name']

Dharma
  • 2,425
  • 3
  • 26
  • 40
-1

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

import module_name
dir(module_name)

You can also pass an object to dir() as

dir(object_name)

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-1

Here's a nice one liner (but will get attributes as well):

print(*dir(obj), sep='\n')
Zack Plauché
  • 3,307
  • 4
  • 18
  • 34