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.

11
  • 2
    Does this answer your question? What is a "callable"? Commented Jun 22, 2020 at 18:44
  • 2
    The return value of outer() is a function. That's why it's callable. Commented Jun 22, 2020 at 18:44
  • 2
    foo is just a name for an object like any other name. inner is a name for a function. Commented Jun 22, 2020 at 18:45
  • 2
    A variable can point to a function like it can point to anything else. Commented Jun 22, 2020 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. Commented Jun 22, 2020 at 18:58

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

This has little to do with being object-oriented; it's more about how Python's data model is defined. Variables are names associated with values, rather than named locations in memory.
That's true too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.