简体   繁体   中英

Pytest: approx() with >, <, <=, and >=

So the documentation for pytest states the following:

Warning:
Changed in version 3.2.

In order to avoid inconsistent behavior, TypeError is raised for > , >= , < and <= comparisons. The example below illustrates the problem:

 assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10) assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10) 

In the second example one expects approx(0.1).__le__(0.1 + 1e-10) to be called. But instead, approx(0.1).__lt__(0.1 + 1e-10) is used to comparison. This is because the call hierarchy of rich comparisons follows a fixed behavior.

Now I don't know if I'm being stupid, but why would one expect __le__ in the second example? I definitely don't. I expect __lt__ .

I don't know what this is trying to state honestly. And I can't see why the functions can't be something like:

def __gt__(self, actual):
    return actual > self.expected and other != self

def __lt__(self, actual):
    return actual < self.expected and other != self

with the __ge__ and __le__ variants using or instead of and .

approx is meant to be used when you are comparing float type numbers with == != operators to avoid the confusing examples of 0.1 + 0.2 != 0.3

the provided example should be interpreted like if the user wanted to answer is 0.1000000001 bigger than 0.1 ? the answer you expect is True

now if you use approx it would say False since 0.1000000001 == approx(0.1) (if you used __le__ it would say True - that is why they wrote __le__ is expected)

so using approx - a kind of fuzzy number and greater/less than ranges is not intuitive - questions like is X larger than about 7 are not generally used and if you need a wierd fuzzy ranges you should state it explicitly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM