I know it's not that bad, but I can't help but wonder if there is a way to make this DRY-er.
s = self.start
e = self.end
if s.x > e.x:
s.x, e.x = e.x, s.x
if s.y > e.y:
s.y, e.y = e.y, s.y
I know it's not that bad, but I can't help but wonder if there is a way to make this DRY-er.
s = self.start
e = self.end
if s.x > e.x:
s.x, e.x = e.x, s.x
if s.y > e.y:
s.y, e.y = e.y, s.y
You basicaly want to sort your data, you may be interested in sorted
then:
start = self.start
end = self.end
start.x, end.x = sorted((start.x, end.x))
start.y, end.y = sorted((start.y, end.y))
You can make use of getattr()
and setattr()
built-in functions, handling any potential number of attributes to swap:
start = self.start
end = self.end
attrs = ["x", "y"]
for attr in attrs:
start_attr_value, end_attr_value = getattr(start, attr), getattr(end, attr)
if start_attr_value > end_attr_value:
setattr(start, attr, end_attr_value)
setattr(end, attr, start_attr_value)
Also note the more explicit start
and end
variable names in place of s
and e
. I've abbreviated attribute
as attr
, but you may go for the full word if you prefer.
You may then extract this into a separate method/function for reusability and readability:
def swap_attributes(start, begin, attrs):
"""Meaningful docstring here."""
for attr in attrs:
start_attr_value, end_attr_value = getattr(start, attr), getattr(end, attr)
if start_attr_value > end_attr_value:
setattr(start, attr, end_attr_value)
setattr(end, attr, start_attr_value)
Usage:
swap_attributes(self.start, self.begin, attrs=["x", "y"])
Or may be merge_ranges
would be a better name for the function (depending on the actual problem you are solving with it).