4

Since everything is an object in Python (even functions) is it possible to actually extend from function class? For example I can do the following with string type. Is there any way to do something similar on function type?

class Foo(str):
    def appendFoo(self):
        return self+'foo'

foo = Foo('test')
print foo
>>> test
print foo.upper()
>>> TEST
print foo.appendFoo()
>>> testfoo
marcin_koss
  • 5,763
  • 10
  • 46
  • 65
  • Could you clarify what you mean, possibly adding examples as well? – Volatility Feb 26 '13 at 05:55
  • @Volatility I'm just exploring the language and wondering if something like that was possible. Thanks. – marcin_koss Feb 26 '13 at 06:01
  • 1
    Related: http://stackoverflow.com/questions/10061752/which-classes-cannot-be-subclassed – John Y Feb 26 '13 at 06:05
  • Incidentally, while you can't subclass a function, you *can* add attibutes to function instances. Not that this is necessarily useful, but it's kind of fun (and maybe a little funny). – John Y Feb 26 '13 at 06:07
  • You could do something creative and probably very slow involving `__call__` that would be extensible and would delegate to any function. – minopret Feb 26 '13 at 06:11

1 Answers1

2

Nope, I wish. You are stuck with functors.

>>> def f(): pass
...
>>> type(f)
<type 'function'>
>>> function
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> function = type(f)
>>> class MyFunc(function):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    type 'function' is not an acceptable base type
>>> type('MyFunc', (function,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'function' is not an acceptable base type
pyrospade
  • 7,870
  • 4
  • 36
  • 52