0

Suppose I have the following code:

def my_func(input_line):

    is_skip_line = self.is_skip_line(input_line)  # parse input line check if skip line

    if is_skip_line:
        # do something...

    # do more ...

    if is_skip_line:
        # do one last thing

So we have a check for is_skip_line (if is_skip_line:) that appears twice. Does it mean that due to lazy evaluation the method self.is_skip_line(input_line) will be called twice?

If so, what is the best work around, given that self.is_skip_line(input_line) is time consuming? Do I have to "immediately invoke" it, like below?

is_skip_line = (lambda x: self.is_skip_line(x))(input_line)

Thanks.

3
  • 7
    This is not a lazily evaluating statement in Python. The only situation in which Python really lazily evaluates is with generators. self.is_skip_line(input_line) will only ever be evaluated once. Commented May 23, 2015 at 19:52
  • 2
    is_skip_line is evaluated twice, but self.is_skip_line(input_line) is only evaluated once. Commented May 23, 2015 at 20:09
  • 2
    Why do you think wrapping a function call in a lambda, then applying it to an argument, would be any less lazy than simply applying the call? Commented May 23, 2015 at 20:17

1 Answer 1

1

The misconception here is that this statement is not being immediately invoked:

is_skip_line = self.is_skip_line(input_line)

...when in fact, it is.

The method self.is_skip_line will only ever be invoked once. Since you assign it to a variable, you can use that variable as many times as you like in any context you like.

If you're concerned about the performance of it, then you could use cProfile to really test the performance of the method it's called in with respect to the method it's calling.

Sign up to request clarification or add additional context in comments.

Comments

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.