Function without parameter

In one example scripts abt sorting certain panels I saw on net, its like this:


def getkey(panel):
    return key

sortP=sorted(panels,key= getkey)

My question is that in the last step, why the defined function getkey is without the parameter? (11.0 KB)

The optional key parameter allows you to specify a function that gets then called on each of the items in the list to be sorted, here panels. The return values of this function are then used to sort the list items by.
It already knows by design what it has to do, namely applying the key function to each item in panels. You’re only referencing which function to use, not calling it explicitly. That’s done during the sorting process “internally”.

1 Like

Thx a lot arch. But how could I know that this parameter is optional?Is there any hint or rule indicating this?

You can always check out the Python documentation to know how specific standard, built-in functions work. It has examples and explanations for everything.

In general, when you define a function in Python, all parameters that are already passed arguments (values) during definition are considered optional. These parameters are considered to be default ones.

def get_point(x, y, z=0.0):   # parameter z if optional, it's default value is 0.0
    return (x, y, z)
1 Like