forked from Hultner/Python-Data-Classes-Talk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
95 lines (75 loc) · 2.92 KB
/
demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import collections
from datetime import date, datetime
from typing import List, Optional
from dataclasses import dataclass, field, asdict, astuple
import jsondate as json
@dataclass
class Host:
name: str # Required field
nickname: Optional[str] = None # Optional field not required
@dataclass
class Event:
title: str # Required field
# Mutable objects requires a factory, otherwise they'll share state just
# like conventional Python classes. A suggestion to change this was rejected.
hosts: List[Host] = field(default_factory=list)
day: date = field(default_factory=date.today)
# Executes after init, good for *validation* and *post processing*
def __post_init__(self):
# Transform host dict/mappings to instances of host class
self.hosts = [Host(**hoster) for hoster in self.hosts]
# Named tuple approach
EventHacky = collections.namedtuple("EventBad", ["title", "hosts", "day"])
class EventConventionalVerbose:
def __init__(self, title: str, hosts: Host = None, day: date = None):
self.title = title
# Can't set mutable objects as default argument
if hosts is None:
self.hosts = []
else:
self.hosts = [Host(**hoster) for hoster in hosts]
if day is None:
self.day = date.today()
else:
self.day = day
def __repr__(self):
return f"EventConventionalVerbose(title={self.title!r}, hosts={self.hosts!r}, day={self.day!r})"
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.title, self.hosts, self.day) == (
other.title, other.hosts, other.day
)
return NotImplemented
def __ne__(self, other):
if other.__class__ is self.__class__:
return (self.title, self.hosts, self.day) != (
other.title, other.hosts, other.day
)
return NotImplemented
def __lt__(self, other):
if other.__class__ is self.__class__:
return (self.title, self.hosts, self.day) < (
other.title, other.hosts, other.day
)
return NotImplemented
def __le__(self, other):
if other.__class__ is self.__class__:
return (self.title, self.hosts, self.day) <= (
other.title, other.hosts, other.day
)
return NotImplemented
def __gt__(self, other):
if other.__class__ is self.__class__:
return (self.title, self.hosts, self.day) > (
other.title, other.hosts, other.day
)
return NotImplemented
def __ge__(self, other):
if other.__class__ is self.__class__:
return (self.title, self.hosts, self.day) >= (
other.title, other.hosts, other.day
)
return NotImplemented
host_collection = [
{"name": "Alexander Hultnér", "nickname": "Hultnér"}, {"name": "Emily Bache"}
]