Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please what does func() mean in python when used inside a function

Please what does func() mean in python when used inside a function,For example in the code below.

def identity_decorator(func):
    def wrapper():
        func()
    return wrapper
like image 868
king alua Avatar asked Nov 30 '14 23:11

king alua


People also ask

What is called when a function called inside a function in Python?

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.

Can you put a function inside a function Python?

They can be created and destroyed dynamically, passed to other functions, returned as values, etc. Python supports the concept of a "nested function" or "inner function", which is simply a function defined inside another function.

How do you call a Func in Python?

Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters. >>> greet('Paul') Hello, Paul.


2 Answers

I was wondering the same! You can see how it works with the follow example:

def make_pretty(func):
    def inner():
       print("I got decorated")
       func()
    return inner

def ordinary():
    print("I am ordinary")

pretty = make_pretty(ordinary)
pretty()

Output
I got decorated
I am ordinary 

Now when you remove the func() and you try to rerun it:

def make_pretty(func):
    def inner():
       print("I got decorated")
    return inner

def ordinary():
    print("I am ordinary")

pretty = make_pretty(ordinary)
pretty()

Output
I got decorated

You see the the decorated function was not called. Please have a look here https://www.programiz.com/python-programming/decorator

like image 160
Alex Avatar answered Sep 25 '22 23:09

Alex


func is an argument given to the function identity_decorator().

The expression func() means "call the function assigned to the variable func."

The decorator is taking another function as an argument, and returning a new function (defined as wrapper) which executes the given function func when it is run.

Here is some information about decorators.

like image 26
khelwood Avatar answered Sep 21 '22 23:09

khelwood