6q9nqBjo
6q9nqBjo

Reputation: 191

Get attributes from a returned function in Python

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.

Upvotes: 1

Views: 44

Answers (2)

MMN
MMN

Reputation: 676

  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.

Upvotes: -1

user2357112
user2357112

Reputation: 281958

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.

Upvotes: 3

Related Questions