Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python function or method that displays object specifications?

Tags:

python

Is there a built-in method for getting specification comments in Python that can be used instead of going back and reading them in the class definition? Specifically I'm trying to identify how many and what sort of arguments a object from an imported module takes.

I couldn't find an answer to this in the Python documentation and if it's already been answered on here I couldn't get it in search.

like image 403
mmartinson Avatar asked Dec 26 '22 11:12

mmartinson


2 Answers

>>> from random import randint
>>> help(randint)


Help on method randint in module random:

randint(self, a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.
(END)

http://docs.python.org/2.7/library/functions.html#help

with a custom class:

>>> class Test(object):
...     def __init__(self, smile):
...             print(smile)
...
>>> help(Test)

Help on class Test in module __main__:

class Test(__builtin__.object)
 |  Methods defined here:
 |  
 |  __init__(self, smile)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
(END)
like image 62
dm03514 Avatar answered Dec 28 '22 00:12

dm03514


You can also use inspect module, specifically inspect.getmembers():

inspect.getmembers(object[, predicate])

Return all the members of an object in a list of (name, value) pairs sorted by name.

Example:

>>> import inspect
>>> class Test(object):
...     def __init__(self, smile):
...         print(smile)
... 
>>> inspect.getmembers(Test, predicate=inspect.ismethod)
[('__init__', <unbound method Test.__init__>)]
like image 30
alecxe Avatar answered Dec 28 '22 02:12

alecxe