errorhandler
errorhandler

Reputation: 1767

Is there a Python equivalent to Ruby's respond_to?

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?

Upvotes: 11

Views: 4716

Answers (4)

Constantinius
Constantinius

Reputation: 35069

I am no Ruby expert, so I am not sure if this answers your question. I think you want to check if an object contains a method. There are numerous ways to do so. You can try to use the hasattr() function, to see if an object hast the method:

hasattr(fun, "hello") #True

Or you can follow the python guideline don't ask to ask, just ask so, just catch the exception thrown when the object doesn't have the method:

try:
    fun.hello2()
except AttributeError:
    print("fun does not have the attribute hello2")

Upvotes: 1

log0
log0

Reputation: 10917

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.

Upvotes: 8

Jim Dennis
Jim Dennis

Reputation: 17510

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).

Upvotes: 17

yurib
yurib

Reputation: 8147

dir(instance) returns a list of an objects attributes.
getattr(instance,"attr") returns an object's attribute.
callable(x) returns True if x is callable.

class Fun(object):
    def hello(self):
        print "Hello"

f = Fun()
callable(getattr(f,'hello'))

Upvotes: 2

Related Questions