Home > Net >  How did my variable turn into a function?
How did my variable turn into a function?

Time:06-14

Hello fellow S Overflowers. This question might seem dumb to some, but I cannot express how much asking these conceptual questions has helped me understand coding in general and for that I want to preface the question saying I appreciate all of you very much!!

My doubt here is: How did the variable Twice at the end, turned into a function call to which I could put parentheses on. How could a variable start behaving as a function?

Apologies if this is obvious to some, but I'd love some human explaining because being new to the scene, documentation jargon gets pretty complicated.

#Define echo
def echo(n):
    """Return the inner_echo function."""

    # Define inner_echo
    def inner_echo(word1):
        """Concatenate n copies of word1."""
        echo_word = word1 * n
        return echo_word

    # Return inner_echo
    return(inner_echo)

#Call echo: twice        
twice = echo(2)
    
#Call twice() and print
print(twice('hello'))

CodePudding user response:

In the echo function, you are returning inner_echo, which is pointer to a function, not its return value. In order to return the output of inner_echo you need to call it.

...
    # Return inner_echo value
    return(inner_echo(word))
...

You returned the nested function object, so twice becomes function object of inner_echo encapsulated in the enviroment from which it was returned. It means python saves the n variable, which does not exist inside inner_echo and twice becomes inner_echo function with given n value (2 in your example).

This would be unsafe code in other languages, which don't save the eviroment variables, however python does this implicitly.

CodePudding user response:

In Python variables can hold numbers, strings, functions, objects, even modules. You can put just about anything in a variable.

When you do return(inner_echo), inner_echo is a function. That's how you ended up with a function. If you did return(inner_echo(word1)), then the variable twice would end up containing 'hellohello' which might be more in line with what you're expecting.

  • Related