frederick_otus
frederick_otus

Reputation: 75

Choosing a function based on parameter types in python

I have a function that is taking an arbitrary set of arguments and then choosing the correct function to process them based on the types of the arguments.

My current approach is using a decorator on all of the processing functions that checks the types of the arguments, and then iterating through all of the functions until one accepts the arguments.

Something about this seems a little hacky to me, and as a relatively new python programmer, I was wondering if there was a more 'pythonic' method to doing this.

so, currently, I have something like this:

def function_router(*args):
   for func in functions: #functions is a list of functions
      try:
         return func(*args)
      except TypeError:
         pass
    #probably raise an exception if no function works

and each function in 'functions' would have a decorator like this:

def accepts(*types) :
   def my_decorator(func):
      def wrapped(*args, **kwargs):
         for i in range(len(types)):
            if not isinstance(args[i], types[i]):
               raise TypeError('Type error, %s not instance of %s, it is %s' %(args[i],types[i], type(args[i])))
            return func(*args, **kwargs)
      return wrapped
   return my_decorator

EDIT: Oh man, I actually really liked reading all of the solutions. The answer I chose was most effective for what I'm currently doing, but I learned something from all of the answers, so thank you all for your time.

Upvotes: 2

Views: 2353

Answers (2)

SingleNegationElimination
SingleNegationElimination

Reputation: 156238

It sounds like you're trying to describe multimethods, for which GvR has provided a nice recipe in the form of a decorator.

Upvotes: 2

nmichaels
nmichaels

Reputation: 50991

Perhaps the right way to do this is to use keyword arguments, instead of relying on the types of the arguments. That way, you don't have to decorate the little functions, just name the arguments correctly. It will also let you take advantage of Python's duck typing.

Upvotes: 4

Related Questions