Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function vs argument
#1
I am trying to wrap my head around a piece of code from a text. Its a prelude to decorators, and apparently crucial to an understanding of them. But the example is rudimentary:

from time import sleep, time

def f():
    sleep(.3)
def g():
    sleep(.5)
def measure(func):  #A
    t = time()
    func()                 #B
    print(func.__name__, 'took:', time() - t)

measure(f) # f took: 0.30434322357177734
measure(g) # g took: 0.5048270225524902
The problem I am having is that the named parameter and the function are not seperable. 'func' at #A appears required to define func() at #B.

And func() as a function call is calling an argument?

Utterly, totally confused at this point.....

What does one *call* this?
Reply
#2
One calls this "functions as first class objects." This means that functions can be passed as arguments, assigned as values, put into lists, and so on. Note that hash(f) returns a value, so functions are hashable and can be put into sets and used as keys in dictionaries.

So measure(f) calls the function measure and passes f as the only parameter. So f is the func parameter, and within that call, func == f. So when func is called with func(), it is calling f.

The key is that if you don't have the parenthesis after it, it's just the function object. The parenthesis are actually an operator, the call operator. If you look up a table of operator precedence in Python, they should be on the list. So f is just the function object, and f() is the call operator applied to the function object, which runs the code.

It reminds me of Linear Algebra and vector spaces of functions. That was a cool subject.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
A function that either takes a function as a parameter, or returns one is called a higher order function.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Decorator for a function with argument(s) banidjamali 1 1,826 Feb-09-2021, 11:55 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020