Tuples and Ternary and positional parameters

Viewed 254

Given:

>>> a,b=2,3
>>> c,d=3,2
>>> def f(x,y): print(x,y)

I have an existing (as in cannot be changed) 2 positional parameter function where I want the positional parameters to always be in ascending order; i.e., f(2,3) no matter what two arguments I use (f(a,b) is the same as f(c,d) in the example)

I know that I could do:

>>> f(*sorted([c,d]))
2 3

Or I could do:

>>> f(*((a,b) if a<b else (b,a)))
2 3

(Note the need for tuple parenthesis in this form because , is lower precedence than the ternary...)

Or,

def my_f(a,b):
    return f(a,b) if a<b else f(b,a)

All these seem kinda kludgy. Is there another syntax that I am missing?


Edit

I missed an 'old school' Python two member tuple method. Index a two member tuple based on the True == 1, False == 0 method:

>>> f(*((a,b),(b,a))[a>b])
2 3

Also:

>>> f(*{True:(a,b), False:(b,a)}[a<b])
2 3

Edit 2

The reason for this silly exercise: numpy.isclose has the following usage note:

For finite values, isclose uses the following equation to test whether two floating point values are equivalent.

absolute(a - b) <= (atol + rtol * absolute(b))

The above equation is not symmetric in a and b, so that isclose(a, b) might be different from isclose(b, a) in some rare cases.

I would prefer that not happen.

I am looking for the fastest way to make sure that arguments to numpy.isclose are in a consistent order. That is why I am shying away from f(*sorted([c,d]))

3 Answers
Related