AxelG
AxelG

Reputation: 37

Looping over operator

I am writing a test for a type class and I was wondering if there is a way of looping and changing the operator? so loop over [+, -, *, / , // ]

so what I want to do is :

for op in operators:
 assert 2 op my_type == 2 op my_type.num_atr # op being the operator +, - etc 

so this would the same as

assert 2 + my_type == 2 + my_type.num_atr
assert 2 - my_type == 2 - my_type.num_atr
assert 2 * my_type == 2 * my_type.num_atr
# ....

Is this somehow possible? I understand that this somewhat just syntactic sugar and that there are not too many operators but this would make it faster to change all of the tests at the same time.

Upvotes: 0

Views: 59

Answers (1)

Aaron
Aaron

Reputation: 1368

How about operator module? Or write simply the operation as function.

import operator

for op in (
    operator.add,
    operator.sub,
    operator.mul,
    operator.div,
    operator.floordiv,
):
    assert op(2, my_type) == op(2, my_type.num_atr)  # op being the operator +, - etc

Upvotes: 3

Related Questions