6q9nqBjo 6q9nqBjo - 2 months ago 6
Python Question

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.

Answer

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.

Comments