Access the methods of a class

Discussion in 'Python' started by Fernando Rodriguez, Oct 31, 2003.

  1. Hi,

    I have a base class with a 'sanity-check' method. This method should iterate
    through all the methods and check if they are all 'thunks' (zero parameter
    functions, well actually, 1 parameter: self).

    How can I access the list of methods of a given object? BTW, this class will
    be inherited from, so it should work with hte derived classes too.

    How can I check the number of parameters of a given function object?

    TIA O:)

    PS Any pointers to a python reflection tutorial, would also be appreciated.
    Fernando Rodriguez, Oct 31, 2003
    #1
    1. Advertising

  2. Fernando Rodriguez

    Gary Herron Guest

    On Friday 31 October 2003 08:10 am, Fernando Rodriguez wrote:
    > Hi,
    >
    > I have a base class with a 'sanity-check' method. This method should
    > iterate through all the methods and check if they are all 'thunks' (zero
    > parameter functions, well actually, 1 parameter: self).
    >
    > How can I access the list of methods of a given object? BTW, this class
    > will be inherited from, so it should work with hte derived classes too.
    >
    > How can I check the number of parameters of a given function object?
    >
    > TIA O:)
    >
    > PS Any pointers to a python reflection tutorial, would also be appreciated.


    The inspect module should provide everything you need here.

    >From the manual:



    inspect -- Inspect live objects

    New in version 2.1.


    The inspect module provides several useful functions to help get
    information about live objects such as modules, classes, methods,
    functions, tracebacks, frame objects, and code objects. For
    example, it can help you examine the contents of a class, retrieve
    the source code of a method, extract and format the argument list
    for a function, or get all the information you need to display a
    detailed traceback.


    Gary Herron
    Gary Herron, Oct 31, 2003
    #2
    1. Advertising

  3. Fernando Rodriguez wrote:

    > Hi,
    >
    > I have a base class with a 'sanity-check' method. This method should
    > iterate through all the methods and check if they are all 'thunks' (zero
    > parameter functions, well actually, 1 parameter: self).
    >
    > How can I access the list of methods of a given object? BTW, this class
    > will be inherited from, so it should work with hte derived classes too.
    >
    > How can I check the number of parameters of a given function object?
    >
    > TIA O:)
    >
    > PS Any pointers to a python reflection tutorial, would also be
    > appreciated.


    Check out module inspect in the standard library. It does the job
    AND it's great example code for the actual lower-level mechanisms
    Python offers for reflection.

    >>> class base(object):

    .... def a(self): pass
    .... def b(self): pass
    .... def c(self): pass
    ....
    >>> class deriv(base):

    .... def c(self): pass
    .... def d(self): pass
    ....
    >>> import inspect as i
    >>> i.getmembers(deriv, i.ismethod)

    [('a', <unbound method deriv.a>), ('b', <unbound method deriv.b>), ('c',
    <unbound method deriv.c>), ('d', <unbound method deriv.d>)]
    >>> for name, method in i.getmembers(deriv, i.ismethod):

    .... print name, len(i.getargspec(method)[0])
    ....
    a 1
    b 1
    c 1
    d 1

    there -- you have the methods and the number of arguments for each.

    You can also easily do more refined checks, e.g. if a method takes
    *args or **kwargs the [1] and [2] items of the tuple getargspec
    returns about it are going to be non-None, and in the [3] item you
    have a tuple of default values so you know how many of the [0] argument
    names are optional...


    Alex
    Alex Martelli, Oct 31, 2003
    #3
  4. On Fri, 31 Oct 2003 17:10:21 +0100, Fernando Rodriguez <> wrote:

    >Hi,
    >
    >I have a base class with a 'sanity-check' method. This method should iterate
    >through all the methods and check if they are all 'thunks' (zero parameter
    >functions, well actually, 1 parameter: self).
    >
    >How can I access the list of methods of a given object? BTW, this class will
    >be inherited from, so it should work with hte derived classes too.
    >
    >How can I check the number of parameters of a given function object?
    >
    >TIA O:)
    >
    >PS Any pointers to a python reflection tutorial, would also be appreciated.


    I don't know off hand how to get the parameter count for built in methods, but:

    >>> class A(object):

    ... def m_a1(self):pass
    ... def m_a2(self, two):pass
    ... def m_a3(self, two, three=3):pass
    ...
    >>> class Foo(A, list):

    ... def m1(self): print 'm1'
    ... def m2(self): print 'm2'
    ... notamethod = 'not a method'
    ... def sanity(self):
    ... for name in dir(type(self)):
    ... if not name.startswith('_'):
    ... x = getattr(self, name)
    ... if callable(x):
    ... nargs = hasattr(x,'func_code') and x.func_code.co_argcount or '??'
    ... print '%s has %s parameter%s' % (name, nargs, 's'[:nargs!=1] )
    ... def twoarg(self, two): pass
    ... def threearg(self, two, three): pass
    ...
    >>> foo = Foo()
    >>> foo.sanity()

    append has ?? parameters
    count has ?? parameters
    extend has ?? parameters
    index has ?? parameters
    insert has ?? parameters
    m1 has 1 parameter
    m2 has 1 parameter
    m_a1 has 1 parameter
    m_a2 has 2 parameters
    m_a3 has 3 parameters
    pop has ?? parameters
    remove has ?? parameters
    reverse has ?? parameters
    sanity has 1 parameter
    sort has ?? parameters
    threearg has 3 parameters
    twoarg has 2 parameters

    Regards,
    Bengt Richter
    Bengt Richter, Oct 31, 2003
    #4
  5. Fernando Rodriguez

    Terry Reedy Guest

    "Fernando Rodriguez" <> wrote in message
    news:...
    > Hi,
    >
    > I have a base class with a 'sanity-check' method. This method should

    iterate
    > through all the methods and check if they are all 'thunks' (zero

    parameter
    > functions, well actually, 1 parameter: self).


    If you want to enforce 'sanity' rather than post-check, you might be
    able to use a custom metaclass -- which gets the dictionary of
    attributes as an argument. But that is an expert project not for the
    faint of heart.

    tjr
    Terry Reedy, Nov 1, 2003
    #5
  6. Terry Reedy wrote:

    >> I have a base class with a 'sanity-check' method. This method should

    > iterate
    >> through all the methods and check if they are all 'thunks' (zero

    > parameter
    >> functions, well actually, 1 parameter: self).

    >
    > If you want to enforce 'sanity' rather than post-check, you might be
    > able to use a custom metaclass -- which gets the dictionary of
    > attributes as an argument. But that is an expert project not for the
    > faint of heart.


    I am not a cardiologist, but I think you're emphasizing the difficulties
    too much. Suppose we have a checking function that does the "atomic"
    check on one function-that's-about-to-become-a-method (I showed how to
    do that with inspect in a previous post) -- say a function 'dockeck'
    which is called with the name and corresponding functionobject and raises
    an appropriate exception if they're somehow "not right". Then packaging
    the use of this function in a custom metaclass is not hard at all:

    class MetaChecker(type):
    def __new__(mcl, clasname, clasbases, clasdict):
    for name, value in clasdict.iteritems():
    if callable(value): docheck(name, value)
    return type.__new__(mcl, clasname, clasbases, clasdict)

    class Checked: __metaclass__ = MetaChecker


    that's all -- just inherit your classes from Checked rather than from object
    and all of the classes' callable attributes will be subject to whatever
    checking docheck performs at class-object-creation time. (Easy to tweak if
    you don't want to check all callables, again see standard module inspect
    for what you can easily find out about the items in clasdict).

    For anybody doing reasonably advanced things such as reflection and the
    like -- and the original poster did indicate that such things were exactly
    his goal -- it does not seem to me that such well-bounded and simple use
    of a custom metaclass should prove forbiddingly hard or heart-threatening.


    Alex
    Alex Martelli, Nov 1, 2003
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. E11
    Replies:
    1
    Views:
    4,750
    Thomas Weidenfeller
    Oct 12, 2005
  2. John M. Gabriele
    Replies:
    18
    Views:
    1,153
    Steven Bethard
    Feb 18, 2005
  3. Oltmans
    Replies:
    6
    Views:
    341
    Terry Reedy
    Mar 11, 2009
  4. DG
    Replies:
    3
    Views:
    334
    Terry Reedy
    Jul 22, 2009
  5. Kenneth McDonald
    Replies:
    5
    Views:
    313
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page