Get Class Methods with Python

By  on  

As a newbie to the excellent world of Python development, I'm not always familiar with the methods provided by imported classes.  Oftentimes these classes are well-documented but in the case that methods aren't documented, I found the dir function useful for getting a list of methods:

# dir({object})
dir(difflib)

"""
Returns:

['Differ', 'HtmlDiff', 'IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'Match', 'SequenceMatcher', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_calculate_ratio', '_count_leading', '_file_template', '_legend', '_mdiff', '_namedtuple', '_styles', '_table_template', '_test', 'context_diff', 'get_close_matches', 'heapq', 'ndiff', 'reduce', 'restore', 'unified_diff']

"""

The snippet above does exactly what you would expect -- provides a list of method names for the viewing!

Recent Features

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • By
    Welcome to My New Office

    My first professional web development was at a small print shop where I sat in a windowless cubical all day. I suffered that boxed in environment for almost five years before I was able to find a remote job where I worked from home. The first...

Incredible Demos

Discussion

  1. hwiechers

    Isn’t this normall done with dir(difflib)?

    • That does the same thing but alphabetizes the result. Thanks for mentioning that!

  2. Jasper

    It does not do the same thing. dir(my_object) will show you everything you can do on the instance, including methods on the class, and superclasses. __dict__ will only show you the unique things that belong to the object, which isn’t very many.

    • Thanks for the additional information Jasper! I’ve updated my post!

  3. Marcin

    You can also use bpython shell which is a nice alternative to ipython and standard python ones. It has auto-completion which displays all available methods and attributes on any object. It can be installed in virtualenv with pip install bpython.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!