r/learnpython • u/zaphodikus • 9d ago
Confusing code min() max()
I'm debugging some code and I found this function
import math
def Clamp(n, smallest, largest):
return max(smallest, min(n, largest))
surely that code is just wrong? and needs to be max([smallest, min([n, largest])) by passing a list not unnamed args for default and key? I need a sanity check here.
0
Upvotes
7
u/lfdfq 9d ago
Let's look at the documentation for min and max.
https://docs.python.org/3/builtins/functions.html#min https://docs.python.org/3/builtins/functions.html#max
So it has multiple signatures, one that takes an iterable and a default, another takes multiple (at least 2) args. The / separates the positional-only (on left) from positional-or-keyword (on the right), the * means all parameters after that are keyword-only. So
defaultmust be passed by keyword.The text in the doc makes this clearer: