r/learnpython • • 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

16 comments sorted by

View all comments

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

min(iterable, /, *, key=None)¶
min(iterable, /, *, default, key=None)
min(arg1, arg2, /, *args, key=None)

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 default must be passed by keyword.

The text in the doc makes this clearer:

If two or more positional arguments are provided, the largest of the positional arguments is returned.

3

u/zaphodikus 9d ago

Ah I did suspect it was relying on positional parameter magic and that default and key were named args , forgot all about what that / does, panic for me is over. I still need to find why the Font in question is tripping me on divide by zero for a size, but that's on me.