Finding what methods a Python object has

PythonIntrospection

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

To check if it has a particular method:

hasattr(object,"method")

Solution 6 - Python

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.

Solution 7 - Python

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)

Solution 8 - Python

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('__')]

Solution 9 - Python

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

Solution 10 - Python

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(

Solution 11 - Python

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.

Solution 12 - Python

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.

Solution 13 - Python

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

This should work :)

Solution 14 - Python

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

Solution 15 - Python

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

Solution 16 - Python

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

Solution 17 - Python

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

Solution 18 - Python

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

Solution 19 - Python

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.

Solution 20 - Python

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.

Solution 21 - Python

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

print(*dir(obj), sep='\n')

Solution 22 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomas L&#246;tzerView Question on Stackoverflow
Solution 1 - PythonljsView Answer on Stackoverflow
Solution 2 - PythonBill the LizardView Answer on Stackoverflow
Solution 3 - PythonPawan KumarView Answer on Stackoverflow
Solution 4 - PythonivanleonczView Answer on Stackoverflow
Solution 5 - PythonfiggView Answer on Stackoverflow
Solution 6 - Pythonjmanning2kView Answer on Stackoverflow
Solution 7 - PythonParitosh VyasView Answer on Stackoverflow
Solution 8 - PythonSergey BushmanovView Answer on Stackoverflow
Solution 9 - PythonpaulmelnikowView Answer on Stackoverflow
Solution 10 - PythonValery RamusikView Answer on Stackoverflow
Solution 11 - PythonCldView Answer on Stackoverflow
Solution 12 - PythonaverView Answer on Stackoverflow
Solution 13 - PythonThe MobView Answer on Stackoverflow
Solution 14 - PythonrevliscanoView Answer on Stackoverflow
Solution 15 - PythonBruno BronoskyView Answer on Stackoverflow
Solution 16 - Pythonjames_womackView Answer on Stackoverflow
Solution 17 - PythonMahdi GhelichiView Answer on Stackoverflow
Solution 18 - PythonSimon PIIView Answer on Stackoverflow
Solution 19 - PythonNick CuevasView Answer on Stackoverflow
Solution 20 - PythonSanmitha SadhishkumarView Answer on Stackoverflow
Solution 21 - PythonZack PlauchéView Answer on Stackoverflow
Solution 22 - PythonDharmaView Answer on Stackoverflow