0

Before I start, let me say I know what I am trying to do is unorthodox and perhaps people will have an aversion to the whole concept, however I am curious as to whether it is possible.

So here is the question.

Given an instance k of a class Kthat has an integer attribute z initialised to zero; can we call a lambda function from within k that modifies k.z?

An example would be simply incrementing k.z from 0 to 1.

I've played around a little to see if I could get it to work, and despite success I have included some of that code below.

class K():
  def __init__(self):
    self.z = 0
    self.functions = [
        lambda : "Returns string",
        lambda : self.z, # returns value of z
        # lambda : self.z+=1, # Fails to execute
    ]

k = K()
print(k.functions[0]())
print(k.functions[1]())
print(k.z)

1 Answer 1

2

lambda expressions can only have simple expressions inside of them. In this case, you could do:

lambda : setattr(self, 'z', self.z + 1)

But this is obviously very ugly, and gives you no benefit over:

def _update_z(): self.z += 1
self.functions = [
    lambda : "Returns string",
    lambda : self.z, # returns value of z,
    _update_z
]
Sign up to request clarification or add additional context in comments.

5 Comments

In a case where there are many functions like _update_z, and they are only being called in one place in the same way, why is it better to separate each of these into their own functions? E.g. say there were 100 of these simple one line functions.
@JohnForbes what do you mean? They always are their own function. a lambda creates a function just like any other. In your particular case, you could go either way shown above. I'm just saying, if you can't get something to work with a lambda, just write a regular function definition statement, lambda is only sugar, it doesnt give you anything special
So I was trying to avoid excessive if branching, so i had implemented a switch like structure with a dictionary where given some signal from an event a particular function would fire. After refactoring most of these functions became very short so I was considering having them in place in the dictionary. Thanks for your thoughts, it is good to know what is possible.
@JohnForbes what? You can still put the function in a dictionary, I'm putting it in a list above...
Yeah, I saw that. I was thanking you for the demonstration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.