12

You'd have already found out by my usage of terminology that I'm a python n00b.

straight forward question:

How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?

potlee
  • 405
  • 1
  • 5
  • 13

9 Answers9

22

Existing answers do a good job of showing you how to get the ATTRIBUTES of an object, but do not precisely answer the question you posed -- how to get the METHODS of an object. Python objects have a unified namespace (differently from Ruby, where methods and attributes use different namespaces). Consider for example:

>>> class X(object):
...   @classmethod
...   def clame(cls): pass
...   @staticmethod
...   def stame(): pass
...   def meth(self): pass
...   def __init__(self):
...     self.lam = lambda: None
...     self.val = 23
... 
>>> x = X()
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
 '__getattribute__', '__hash__', '__init__', '__module__',
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
 'clame', 'lam', 'meth', 'stame', 'val']

((output split for readability)).

As you see, this is giving you the names of all attributes -- including plenty of special methods that are just inherited from object, special data attributes such as __class__, __dict__ and __doc__, per-instance data attributes (val), per-instance executable attributes (lam), as well as actual methods.

If and when you need to be more selective, try:

>>> import inspect
>>> [n for n, v in inspect.getmembers(x, inspect.ismethod)]
['__init__', 'clame', 'meth']

Standard library module inspect is the best way to do introspection in Python: it builds on top of the built-in introspection hooks (such as dir and more advanced ones) to offer you useful, rich, and simple introspection services. Here, for example, you see that only instance and class methods specifically designed by this class are shown -- not static methods, not instance attributes whether callable or not, not special methods inherited from object. If your selectivity needs are slightly different, it's easy to build your own tweaked version of ismethod and pass it as the second argument of getmembers, to tailor the results to your precise, exact needs.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
10

dir( object )

will give you the list.

for instance:

a = 2
dir( a )

will list off all the methods you can call for an integer.

Jon W
  • 15,480
  • 6
  • 37
  • 47
6

Its simple do this for any object you have created

dir(object)

it will return a list of all the attributes of the object.

hj-007
  • 332
  • 3
  • 6
  • 16
5
>>> help(my_object)
  • 2
    This is not actually correct. help is used to display the docstring documentation for a method. e.g. help(string.upper). dir(obj) is what is required. – mikej Sep 04 '09 at 12:38
  • Correct. If something like .methods in Ruby is required, dir(...) is the correct answer. –  Sep 04 '09 at 12:39
  • For interactive use (the OP's use case), this is actually the best approach. The help system will print out the documentation for `my_object`, including a list of all advertised methods (whether or not they have their own docstring). It won't show methods with names that start with `_`, but that's usually ok since such methods are meant for the internal use of the class. – alexis Oct 01 '15 at 15:50
4

Python supports tab completion as well. I prefer my python prompt clean (so no thanks to IPython), but with tab completion.

Setup in .bashrc or similar:

PYTHONSTARTUP=$HOME/.pythonrc

Put this in .pythonrc:

try:
    import readline
except ImportError:
    print ("Module readline not available.")
else:
    print ("Enabling tab completion")
    import rlcompleter
    readline.parse_and_bind("tab: complete")

It will print "Enabling tab completion" each time the python prompt starts up, because it's better to be explicit. This won't interfere with execution of python scripts and programs.


Example:

>>> lst = []
>>> lst.
lst.__add__(           lst.__iadd__(          lst.__setattr__(
lst.__class__(         lst.__imul__(          lst.__setitem__(
lst.__contains__(      lst.__init__(          lst.__setslice__(
lst.__delattr__(       lst.__iter__(          lst.__sizeof__(
lst.__delitem__(       lst.__le__(            lst.__str__(
lst.__delslice__(      lst.__len__(           lst.__subclasshook__(
lst.__doc__            lst.__lt__(            lst.append(
lst.__eq__(            lst.__mul__(           lst.count(
lst.__format__(        lst.__ne__(            lst.extend(
lst.__ge__(            lst.__new__(           lst.index(
lst.__getattribute__(  lst.__reduce__(        lst.insert(
lst.__getitem__(       lst.__reduce_ex__(     lst.pop(
lst.__getslice__(      lst.__repr__(          lst.remove(
lst.__gt__(            lst.__reversed__(      lst.reverse(
lst.__hash__           lst.__rmul__(          lst.sort(
u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101
  • 1
    +1 tab completion makes the standard prompt much more pleasant; I don't know why it's not on by default. You can also put the code in your sitecustomize.py if you like to avoid having to set a STARTUP (although in this case you'd leave out the prints). Note that Windows and Mac users won't have readline by default and will need to download an appropriate module such as pyreadline (Win) or readline.py (Mac). – bobince Sep 04 '09 at 15:04
  • With sitecustomize.py it might influence python applications, while PYTHONSTARTUP in .bashrc makes so that it will only import readline when started from the commandline. This is if I understand sitecustomize.py correctly. – u0b34a0f6ae Sep 04 '09 at 16:02
  • It will, yes, if they use [raw_]input(). This is generally more likely to be a useful thing than to mess anything up, though. – bobince Sep 04 '09 at 23:56
3

For an enhanced version of dir() check out see()!

>>> test = [1,2,3]
>>> see(test)
    []    in    +    +=    *    *=    <    <=    ==    !=    >    >=    hash()
    help()    iter()    len()    repr()    reversed()    str()    .append()
    .count()    .extend()    .index()    .insert()    .pop()    .remove()
    .reverse()    .sort()

You can get it here:

Steven Kryskalla
  • 14,179
  • 2
  • 40
  • 42
2

Do this:

dir(obj)
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
2

Others have mentioned dir. Let me make an remark of caution: Python objects may have a __getattr__ method defined which is called when one attempts to call an undefined method on said object. Obviously dir does not list all those (infinitely many) method names. Some libraries make explicit use of this feature, e.g. PLY (Python Lex-Yacc).

Example:

>>> class Test:
...     def __getattr__(self, name):
...         return 'foo <%s>' % name
...
>>> t = Test()
>>> t.bar
'foo <bar>'
>>> 'bar' in dir(t)
False
Stephan202
  • 59,965
  • 13
  • 127
  • 133
  • ...and carrying on the Ruby analogy from the question, a Ruby class may have overridden method_missing which is called when there is an attempt to call an undefined method and of course obj.methods can't know about method names that are intended to be handled by method_missing. – mikej Sep 04 '09 at 12:46
  • @mikej: thanks! I have no Ruby experience, but when I wrote my answer it did cross my mind that Ruby should have equivalent functionality. – Stephan202 Sep 04 '09 at 12:53
0

If you want only methods, then

def methods(obj):
    return [attr for attr in dir(obj) if callable(getattr(obj, attr))]

But do try out IPython, it has tab completion for object attributes, so typing obj.<tab> shows you a list of available attributes on that object.

Ants Aasma
  • 53,288
  • 15
  • 90
  • 97