1

Hey guys I was referring to an article on decorators and to explain python closures the author used an example like this.

def outer():
    def inner():
        print("Inside inner")

    return inner

foo = outer()
foo() # prints "Inside inner"

The part which is confusing to me is foo is not explicitly a function but a variable. We use paranthesis just to call a funciton.

Calling variable foo as foo() should give an error saying no such function exists according to my understanding of functions.

Tresdon
  • 1,211
  • 8
  • 18
sajeera
  • 31
  • 7
  • 2
    Does this answer your question? [What is a "callable"?](https://stackoverflow.com/questions/111234/what-is-a-callable) – BlackBear Jun 22 '20 at 18:44
  • 2
    The return value of `outer()` is a function. That's why it's callable. – jordanm Jun 22 '20 at 18:44
  • 2
    `foo` is just a name for an object like any other name. `inner` is a name for a function. – Peter Wood Jun 22 '20 at 18:45
  • 2
    A variable can point to a function like it can point to anything else. – jonrsharpe Jun 22 '20 at 18:45
  • 3
    `outer` and `inner` are variables, too - ones whose initial value is a function. In Python, `def` is really just a very specialized form of assignment statement. – jasonharper Jun 22 '20 at 18:58
  • 1
    Take a look at the output of `print(foo)` (not `print(foo())`). – Daniel Walker Jun 22 '20 at 19:01
  • @BlackBear Thanks for your reference,but I could'nt quite understand the explanation.may be I'm missing something fundamental here. – sajeera Jun 22 '20 at 19:02
  • Following up on what @BlackBear said, there are other things besides functions which you can call. E.g., `x = dict()`. – Daniel Walker Jun 22 '20 at 19:03
  • When I run your code and `print(foo)`, I get `.inner at 0x7fec4175d280>`. – Daniel Walker Jun 22 '20 at 19:18
  • @DanielWalker sry,my bad print(foo) returns .inner at 0x7fec4175d280> and print(foo()) executes funtion and also returns NONE.what does it supposed to mean.please bear with me – sajeera Jun 22 '20 at 19:25
  • The return value of `outer` is a function; namely, the `inner` function you created. The variable `foo` is assigned to `inner`. That's why you can call `foo`. It references the `inner` function. That's what that print statement meant. `foo` **is** `inner`. – Daniel Walker Jun 22 '20 at 19:27

1 Answers1

1

foo is a function. You created it with def. If you're still unsure, print type(foo).

Remember that Python is an object-oriented language. That means that "everything is an object", even functions.

You can assign functions to variables, return them as values from other functions, take them as arguments to other functions, etc.

Heck, even modules are objects. Try this

import math

foobar = math
del math

print(foobar.sqrt(5))

or even

def call_sqrt(x):
    return x.sqrt(5)

import math

print(call_sqrt(math))
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45