5. from enum import auto, Enum
from functools import singledispatch
from typing import Any
class Things(Enum):
kind_of_thing = auto()
another_kind = auto()
@singledispatch
def handle(data: Any):
print(f"Dunno what this is: {data}")
@handle.register(Things)
def handle(data: Things):
print(f"Called with a thing! {data}")
6. It all started with enums …
class Things(Enum):
kind_of_thing = auto()
another_kind = auto()
What’s wrong with strings or module-level variables? … Granted, this is nice:
>>> list(Things)
[<Things.kind_of_thing: 1>, <Things.another_kind: 2>]
>>> 1 in Things
False
>>> Things.kind_of_thing in Things
True
7. Dict’s for data – Python ♥ dictionaries, right??
def summarize_hotel(hotel):
print(f"Name: {hotel['name']}")
print(f"Name: {hotel['reviews_conut']}")
# Uh … what else is in ‘hotel’ anyways?
ArgumentParser … ConfigParser … all act as dicts/mappings. As do classes and
objects, actually.
8. Python would never look like this …
class Hotel:
name: str
reviews_count: int
score: float
Wait, what the … – this is in Python 3.6!!
10. Single dispatch. Ugh!
@singledispatch
def handle(data: Any):
print(f"Dunno what this is: {data}")
@handle.register(Things)
def handle_thing(data: Things):
print(f"Called with a thing! {data}")
handle("stuff") # goes to first
handle(Things.kind_of_thing) # goes to second
13. </SARCASM>
● Python 3 is growing up!
● Very useful (optional!) features for …
○ Code that is read more often than written
○ Large projects
● Use Python 3.6!