708

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,6663 gold badges18 silver badges42 bronze badges
asked Aug 29, 2008 at 15:05
1

22 Answers 22

769

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
13.3k20 gold badges58 silver badges92 bronze badges
answered Aug 29, 2008 at 15:09
Sign up to request clarification or add additional context in comments.

6 Comments

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.
@marsh To print the methods: print [method for method in dir(object) if callable(getattr(object, method))].
I'm getting an AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError' when I try to run this. See details at stackoverflow.com/q/54713287/9677043.
To exclude dunder methods: [ m for m in dir(object) if not m.startswith('__')]
Other way using filter: print(list(filter(lambda x: x[0] != '_' and callable(getattr(obj, x)), dir(obj))))
|
387

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.

answered Aug 29, 2008 at 15:36

2 Comments

The "Guide to Python Introspection" link seems to be dead.
@Loveandpeace-JoeCodeswell Thank you. I couldn't find the original resource, so I had to update it with a link to a different article.
166

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

bad_coder
13.3k20 gold badges58 silver badges92 bronze badges
answered Nov 20, 2013 at 16:06

3 Comments

It also displays the attributes of the object, so if you want to specifically find methods, it will not work.
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 <hasattr(object, "method_name"> to further filter it out?
@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 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.
43

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
31.4k22 gold badges110 silver badges134 bronze badges
answered May 26, 2016 at 14:58

1 Comment

Simply brilliant!
35

To check if it has a particular method:

hasattr(object,"method")
Bill the Lizard
407k213 gold badges579 silver badges892 bronze badges
answered Aug 29, 2008 at 15:40

1 Comment

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)):
30

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,3753 gold badges39 silver badges42 bronze badges
answered Apr 26, 2018 at 19:32

Comments

28

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Aug 29, 2008 at 15:47

Comments

26

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('__')]
answered Dec 7, 2020 at 17:38

Comments

22

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 _
11.8k12 gold badges85 silver badges112 bronze badges
answered Jan 29, 2015 at 17:10

2 Comments

Shouldn't you use inspect.getmembers instead of using dir in a list comprehension?
inspect.getmembers(self, predicate=inspect.ismethod) ?
16

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Nov 15, 2017 at 20:56

2 Comments

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
@MaxCoplan I've added the workaround in code for cases where tab-completion is not enabled by default
12

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Dec 9, 2014 at 14:02

Comments

5

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 Sep 16, 2015 at 12:13

Comments

4
import moduleName
for x in dir(moduleName):
 print(x)

This should work :)

Georgy
13.9k7 gold badges69 silver badges79 bronze badges
answered Nov 22, 2019 at 4:10

Comments

3

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Aug 27, 2020 at 16:49

Comments

2

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 Apr 24, 2015 at 15:37

Comments

2

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']
answered Jan 16, 2018 at 15:34

Comments

2

...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
31.4k22 gold badges110 silver badges134 bronze badges
answered Mar 26, 2013 at 14:51

Comments

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")
answered Mar 9, 2018 at 13:11

Comments

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.

answered Apr 13, 2020 at 14:19

1 Comment

What is "shell plus"?
0

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Aug 19, 2020 at 6:20

Comments

0

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

print(*dir(obj), sep='\n')
answered May 23, 2021 at 18:11

Comments

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

answered Jul 21, 2021 at 18:29

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.