Adriaan
Adriaan

Reputation: 715

Delay an evaluation / lazy evaluation in Python

I want to delay the evaluation of a call to a member function of an instance of a class until this instance actually exists.

Minimum working example:

class TestClass:

    def __init__(self, variable_0):
        self.__variable_0 = variable_0

    def get_variable_0(self):
        return self.__variable_0


delayed_evaluation_0 = test_class.get_variable_0()  # What should I change here to delay the evaluation?
test_class = TestClass(3)
print(delayed_evaluation_0.__next__)  # Here, 'delayed_evaluation_0' should be evaluated for the first time.

I tried using lambda, yield and generator parentheses () but I can't seem to get this simple example to work.

How do I solve this problem?

Upvotes: 2

Views: 338

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

a simple lambda works. When called, the function will fetch test_class variable from the current scope, and if it finds it, that will work, like below:

delayed_evaluation_0 = lambda : test_class.get_variable_0()
test_class = TestClass(3)
print(delayed_evaluation_0())

prints 3

Upvotes: 1

Related Questions