Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python equivalent to Ruby's respond_to?

Tags:

python

class

ruby

Is a way to see if a class responds to a method in Python? like in ruby:

class Fun
  def hello
    puts 'Hello'
  end
end

fun = Fun.new
puts fun.respond_to? 'hello' # true

Also is there a way to see how many arguments the method requires?

like image 260
errorhandler Avatar asked May 22 '11 08:05

errorhandler


2 Answers

Hmmm .... I'd think that hasattr and callable would be the easiest way to accomplish the same goal:

class Fun:
    def hello(self):
        print 'Hello'

hasattr(Fun, 'hello')   # -> True
callable(Fun.hello)     # -> True

You could, of course, call callable(Fun.hello) from within an exception handling suite:

try:
    callable(Fun.goodbye)
except AttributeError, e:
    return False

As for introspection on the number of required arguments; I think that would be of dubious value to the language (even if it existed in Python) because that would tell you nothing about the required semantics. Given both the ease with which one can define optional/defaulted arguments and variable argument functions and methods in Python it seems that knowing the "required" number of arguments for a function would be of very little value (from a programmatic/introspective perspective).

like image 190
Jim Dennis Avatar answered Oct 06 '22 10:10

Jim Dennis


Has method:

func = getattr(Fun, "hello", None)
if callable(func):
  ...

Arity:

import inspect
args, varargs, varkw, defaults = inspect.getargspec(Fun.hello)
arity = len(args)

Note that arity can be pretty much anything if you have varargs and/or varkw not None.

like image 42
log0 Avatar answered Oct 06 '22 10:10

log0