1
def outerFunc(number):
    if number < 0:
        def innerFunc(factor):
            return number * factor
    else:
        def innerFunc(summand):
            return number + summand
    return innerFunc

x = outerFunc(-8)
print(x(4))

The result of the print statement is -32, as expected. I'm using Python 3.5.2

I would like to ask two questions regarding this code snippet:

  1. Is it possible to access the inner function's number property, after having bound innerFunc to x with the statement x = outerFunc(-8)? In other words: is it possible to directly access the preserved value of number, in this case -8, after having performed the closure?
  2. Is it good programming style to return a function, depending on the evaluation of an if-statement? Personally, I think there is better approach, but I'm not sure.

Thanks for your help.

2
  • it's not good style to try to access internal structures. Why do you want to get number? Commented Sep 11, 2016 at 17:59
  • You are absolutely right. Accessing those structures is a pretty bad idea. I would never use it in any kind of productive code. In this case I merely seek understanding as to how closures work on the inside. Commented Sep 17, 2016 at 9:25

2 Answers 2

3

Is it possible to access the inner function's number property

It's not a property. You can technically access it, but not in a particularly nice way:

number = x.__closure__[0].cell_contents

Is it good programming style to return a function, depending on the evaluation of an if-statement?

Yeah, it's fine.

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

2 Comments

Thanks for your help. Your suggestion worked just fine. I'm sorry, if I denoted number a property. I'm not sure about the correct term in this context. How would you call it?
@6q9nqBjo: Closure variable.
-1
  1. No.
  2. Rarely, but there are cases where it could make sense. If you have to ask the question, you should probably consider the answer to be 'no,' at least for now.

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.