Talk Notes: Practicality Beats Purity: The Zen Of Python's Escape Hatch?
I gave the talk Practicality Beats Purity: The Zen of Python’s Escape Hatch as part of PyConline AU 2020, the very online replacement for PyCon AU this year. In that talk, I included a few interesting links code samples which you may be interested in:
Links and code samples
- 20 Pythonic Fec^WTheses by Tim Peters, from comp.lang.python The Way of Python
- Fantastic Blocks and Where to Hide Them, from PyCon AU 2019
- PEP 8
- PEP 318 which introduce decorators
@apply
def apply(transform):
def __decorator__(using_this):
return transform(using_this)
return __decorator__
numbers = [1, 2, 3, 4, 5]
@apply(lambda f: list(map(f, numbers)))
def squares(i):
return i * i
print(list(squares))
# prints: [1, 4, 9, 16, 25]
Init.java
public class Init {
public static void main(String[] args) {
System.out.println("Hello, World!")
}
}
@switch
and @case
__NOT_A_MATCHER__ = object()
__MATCHER_SORT_KEY__ = 0
def switch(cls):
inst = cls()
methods = []
for attr in dir(inst):
method = getattr(inst, attr)
matcher = getattr(method, "__matcher__", __NOT_A_MATCHER__)
if matcher == __NOT_A_MATCHER__:
continue
methods.append(method)
methods.sort(key = lambda i: i.__matcher_sort_key__)
for method in methods:
matches = method.__matcher__()
if matches:
return method()
raise ValueError(f"No matcher matches value {test_value}")
def case(matcher):
def __decorator__(f):
global __MATCHER_SORT_KEY__
f.__matcher__ = matcher
f.__matcher_sort_key__ = __MATCHER_SORT_KEY__
__MATCHER_SORT_KEY__ += 1
return f
return __decorator__
if __name__ == "__main__":
for i in range(100):
@switch
class FizzBuzz:
@case(lambda: i % 15 == 0)
def fizzbuzz(self):
return "fizzbuzz"
@case(lambda: i % 3 == 0)
def fizz(self):
return "fizz"
@case(lambda: i % 5 == 0)
def buzz(self):
return "buzz"
@case(lambda: True)
def default(self):
return "-"
print(f"{i} {FizzBuzz}")