1

I have a function that produces another function.

def make_func(greeting):
    def func(name):
        return greeting + " " + name
    return func

>>> say_hello = make_func("Hello")
>>> say_hello("there")
"Hello there"

Elsewhere in the script, I have access to say_hello, but I have no idea what the greeting in that function actually is. I'd like to find out.

name, of course, isn't possible to get because it's specified when the function is called. But greeting is static, because it's defined outside of the function.

Is there some attribute of say_hello I can examine to get the original "Hello"?

snazzybouche
  • 2,241
  • 3
  • 21
  • 51

2 Answers2

2

You can find a good explanation of how inner functions are compiled in python here

Then the easiest way to get the variable is say_hello.__closure__[0].cell_contents

benjibat
  • 21
  • 1
1

You can just store the attribute greeting in func:

def make_func(greeting):
    def func(name):
        return func.greeting + " " + name
    func.greeting = greeting
    return func

say_hello = make_func("Hello")
print(say_hello.greeting)  # Hello
say_hello.greeting = 'Bye'
print(say_hello('there'))  # Bye there
sanyassh
  • 8,100
  • 13
  • 36
  • 70