Extending the 'function' built-in class

Steven D'Aprano steve at pearwood.info
Mon Dec 2 02:01:41 EST 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 
functions.

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

https://duckduckgo.com/html/?q=delegation%20as%20alternative%20to%
20subclassing


You can also add attributes to functions:

def spam():
    pass

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),
    spam)


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):
        pass

func = MyCallable()



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



-- 
Steven



More information about the Python-list mailing list