Extending the 'function' built-in class

Steven D'Aprano steve at pearwood.info
Mon Dec 2 08:01:41 CET 2013

On Sun, 01 Dec 2013 19:18:58 +0000, G. wrote:

> Hi, I can't figure out how I can extend the 'function' built-in class. I
> tried:
>   class test(function):
>     def test(self):
>       print("test")
> but I get an error. Is it possible ?

You cannot subclass the function type directly, but you can extend 

Firstly, rather than subclassing, you can use delegation and composition. 
Google for more info on delegation and composition as an alternative to 


You can also add attributes to functions:

def spam():

spam.eggs = 23

Want to add a method to a function? You can do that too:

from types import MethodType
spam.method = MethodType(
    lambda self, n: "%s got %d as arg" % (self.__name__, n),

It's even simpler if it doesn't need to be a method:

spam.function = lambda n: "spam got %d as arg" % n)

Want more complex behaviour? Write a callable class:

class MyCallable(object):
    def __call__(self, arg):

func = MyCallable()

There are plenty of ways to extend functions. Subclassing isn't one of 


More information about the Python-list mailing list