Larry Diehl
2020-04-10T20:33:06Z

equi_union_types.py

| JSON = Union[None, bool, str, int, List[JSON], Dict[str, JSON]]
|
| def plenty_o_nuttin(x: bool) -> JSON:
| if not x:
| return None
| else:
| return [False, "", 0, {'plenty': ['n', 'u', 't', 't', 'i', 'n']}]

inter_types.py

| HasFirstName = Record(first_name: str)
| HasLastName = Record(last_name: str)
|
| def formal_name(n: Intersection[HasFirstName, HasLastName]) -> str:
| return f"{n.last_name}, {n.first_name}"
|
| person = Person("Mary", None, "Jane")
| formal_name(person) # => "Jane, Mary"

neg_type_ref.py

| def show_double(x: Optional[int]) -> str:
| if isinstance(x, None):
| return ""
| else:
| return str(x * 2)

pos_type_ref.py

| def show_double(x: Optional[int]) -> str:
| if isinstance(x, int):
| return str(x * 2)
| else:
| return ""

record_sub1.py

| @dataclass
| class Person:
| first_name: str
| middle_name: Optional[str]
| last_name: str
|
| def full_name(self) -> str:
| if isinstance(self.middle_name, None):
| return f"{self.first_name} {self.last_name}"
| else:
| return f"{self.first_name} {self.middle_name} {self.last_name}"

record_sub2.py

| # the Person type
| Person = Record(
| first_name: str,
| middle_name: Optional[str],
| last_name: str,
| full_name: Callable[[], str] # function w/o args returning a str
| )
|
| # the Person constructor
| def Person(first: str, middle: Optional[str], last: str) -> Person:
| return <
| first_name = first,
| middle_name = middle,
| last_name = last,
| full_name = lambda: f"{first} {last}" if isinstance(middle, None) else f"{first} {middle} {last}"
| >

record_sub3.py

| person = Person("Mary", None, "Jane")
| person.first_name # => "Mary"
| person.last_name # => "Jane"
| person.full_name() # => "Mary Jane"