0

I want to do something like this in python:

(lambda: ... some code ...).valueHandling(...some parameters)

That is, I want to extend the type function with a new method called valueHandling. I tried different thing like:

1)

def valueHandling(self):
  ...

function.valueHandling=valueHandling

2)

function.__class__.__dict__['valueHandling']=valueHandling

3) etc

None worked... Is there a way to do it? To add a method to function so all 'lambdas' can respond to that method?

Thanks

Yamaneko
  • 3,433
  • 2
  • 38
  • 57
Hernan
  • 71
  • 2

2 Answers2

0

CPython doesn't allow this:

TypeError: can't set attributes of built-in/extension type 'function'

(and if you try to use the .__dict__ method...)

TypeError: 'dictproxy' object does not support item assignment

This is because these types are implemented in C and trade flexibility for speed.

Amber
  • 507,862
  • 82
  • 626
  • 550
0

You can set properties of individual (function/lambda/etc..) objects:

l = lambda x: x*2
def fun():
  return 1
l.f = fun
l.f()
1

You cannot do this for all functions - you have to manually add it to each of them.

You could write a short wrapper, and then mylambda(lambda x: ...) :

def mylambda(x):
  x.f = fun
  return x
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Thank you all! It is a pity Python does not allow you to add functionality to core classes like function... I wanted to do that to implement exception just using objects and without the try/except sintax. I just did it as Karoly suggested. Thanks! – Hernan Oct 17 '12 at 02:27
  • From the documentation: ""Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. Note that the current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future"" – Bakuriu Oct 17 '12 at 13:05