Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic methods in python

Tags:

python

Is it possible to implement generic method handlers in python which allow for calling of non-existent functions? Something like this:

class FooBar:
  def __generic__method__handler__(.., methodName, ..):
    print methodName

fb = FooBar()
fb.helloThere()

-- output --
helloThere
like image 354
paweloque Avatar asked Jun 24 '11 11:06

paweloque


People also ask

What is generic method in Python?

A generic function is composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm. When the implementation is chosen based on the type of a single argument, this is known as single dispatch.

What are generic methods?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

Can functions be generic in Python?

Python has always provided a variety of built-in and standard-library generic functions, such as len() , iter() , pprint. pprint() , copy. copy() , and most of the functions in the operator module.

What is generic function example?

The print() function is an example of a generic function. A generic function is simply a function that performs a common task by dispatching its input to a particular method-function that is selected on the basis of the class of the input to the generic function.


1 Answers

The first thing to remember is that methods are attributes which happen to be callable.

>>> s = " hello "
>>> s.strip()
'hello'
>>> s.strip
<built-in method strip of str object at 0x000000000223B9E0>

So you can handle non-existent methods in the same way you would handle non-existent attributes.

This is usally done by defining a __getattr__ method.

Now you're going hit the additional complexity which is the difference between functions and method. Methods need to be bound to an object. You can take a look at this question for a discussion of this.

So I think you'll want something like this:

import types

class SomeClass(object):
    def __init__(self,label):
        self.label = label

    def __str__(self):
        return self.label

    def __getattr__(self, name):
        # If name begins with f create a method
        if name.startswith('f'):
            def myfunc(self):
                return "method " + name + " on SomeClass instance " + str(self)
            meth = types.MethodType(myfunc, self, SomeClass)
            return meth
        else:
            raise AttributeError()

Which gives:

>>> s = SomeClass("mytest")
>>> s.f2()
'method f2 on SomeClass instance mytest'
>>> s.f2
<bound method SomeClass.myfunc of <__main__.SomeClass object at 0x000000000233EC18>>

However, I'd probably recommend against using this. If you tell us the problem you're trying to solve I expect someone here can come up with a better solution.

like image 200
Dave Webb Avatar answered Sep 24 '22 02:09

Dave Webb