2 ms·
Okay, so if we're talking crimes against Pythonicity, how about avoiding self while still using a class? def Window(x1, x2): minimum = min(x1, x2)
by twic 12y ago
Okay, so if we're talking crimes against Pythonicity, how about avoiding self while still using a class?
def Window(x1, x2):
minimum = min(x1, x2)
maximum = max(x1, x2)
class _(object):
def __call__(_, x):
return minimum <= x <= maximum
return _()
The trick here is that the object instance takes values from its creating context as closure variables, rather than constructor parameters. Hence, it doesn't need a constructor at all, or any self references. It doesn't even need to use the self parameter it implicitly receives - hence why i can call it _ even though Peter Norvig couldn't! I've also called the class _, partly because it's sort of throwaway, in that it's never referred to after the instantiation which immediately follows its declaration, and partly just to wind people up.
You can do this in Java too, using an anonymous class to avoid having to use a throwaway name, as long as the object you're creating implements an interface:
public static Function<Double, Boolean> Window(double x1, double x2) {
double minimum = Math.min(x1, x2);
double maximum = Math.max(x1, x2);
return new Function<Double, Boolean>() {
public Boolean apply(Double x) {
return (minimum <= x) && (x <= maximum);
}
};
}
Neither of these are outlandish hacks; rather, they illustrate the fundamental connection between objects and closures.
In particular, the Java version is extra comical because the interface being implemented is functional, so there is a mechanical transformation (that my IDE will do for me!) which evaporates the anonymous class and uses a naked function, in the form of a lambda, just as the OP advocates:
public static Function<Double, Boolean> Window(double x1, double x2) {
double minimum = Math.min(x1, x2);
double maximum = Math.max(x1, x2);
return x -> (minimum <= x) && (x <= maximum);
}