4 ms·
The author points to this line as the main culprit for self-hell: self.minimum, self.maximum = min(self.minimum, self.maximum), max(self.minimum, self.maximu
by parennoob 12y ago
The author points to this line as the main culprit for self-hell:
self.minimum, self.maximum = min(self.minimum, self.maximum), max(self.minimum, self.maximum)`
This line is needed to 'defensively protect the input'), i.e. try to compensate when minimum and maximum arrive out of order. Firstly, I can't understand exactly why this defensive protection is not done before assigning the attributes, i.e. simply:
# not too hellish, more readable on two lines
self.minimum = min(minimum, maximum)
self.maximum = max(minimum, maximum)
Secondly, I'm not very up on my Python Zen, but I think this naming of arguments followed by defensive protection isn't particularly Pythonic anyway. How about something like this?
class Window(object):
def __init__(self, x1, x2):
# pass your dimensions in any order
self.minimum = min(x1, x2)
self.maximum = max(x1, x2)
def __call__(self, x):
return self.minimum <= x <= self.maximum
- bkeroack 12y agoThe Pythonic solution is named parameters: def __init__(self, min=x, max=y):
- iterati 12y agoThis would also work: def make_window(min, max): min, max = sorted([min, max]) return lambda val: min <= val <= max
- parennoob 12y agoSimple min and max on my computer reliably seems to take less time than the sorted solution, and also makes more sense to read. This is what I would intuitively expect anyway with the overhead of making the array. >>> timeit.timeit('x=4; y=3; x, y = sorted([x, y])') 0.49517297744750977 >>> timeit.timeit('x=4; y=3; x = min(x,y); y = max(x, y)') 0.2774021625518799
- andreasvc 12y agoThe solution of adding the protection first is mentioned but there will be other situations later in which the use of a lot of self cannot be avoided, so it doesn't solve the general problem, if you call it that. What is being called "defensive" I would rather call "permissive". If at all possible, I would prefer raising a ValueError if x1 >= x2.