Slide 1

Slide 1 text

Classy Abstractions Hynek Schlawack

Slide 2

Slide 2 text

[({},),({},)]

Slide 3

Slide 3 text

Primitive Obsession

Slide 4

Slide 4 text

Premature Optimization

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

–me, today “You’re wasting precious resources if you use a high-level language but only use low-level primitives.”

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

PATHLIB

Slide 9

Slide 9 text

PATHLIB >>> p = Path() / "foo" / "bar"

Slide 10

Slide 10 text

PATHLIB >>> p = Path() / "foo" / "bar" >>> p.absolute() PosixPath('/Users/hynek/foo/bar') >>> p.absolute() WindowsPath('C:/Users/Hynek Schlawack/foo/bar')

Slide 11

Slide 11 text

PATHLIB >>> p = Path() / "foo" / "bar" >>> p.absolute() PosixPath('/Users/hynek/foo/bar') >>> p.absolute() WindowsPath('C:/Users/Hynek Schlawack/foo/bar') >>> p.name 'bar'

Slide 12

Slide 12 text

PATHLIB >>> p = Path() / "foo" / "bar" >>> p.absolute() PosixPath('/Users/hynek/foo/bar') >>> p.absolute() WindowsPath('C:/Users/Hynek Schlawack/foo/bar') >>> p.name 'bar' >>> Path("README.md").read_text() ...

Slide 13

Slide 13 text

IPADDRESS

Slide 14

Slide 14 text

IPADDRESS >>> i = ipaddress.ip_address("::1") >>> i.exploded '0000:0000:0000:0000:0000:0000:0000:0001'

Slide 15

Slide 15 text

IPADDRESS >>> i = ipaddress.ip_address("::1") >>> i.exploded '0000:0000:0000:0000:0000:0000:0000:0001' >>> ipaddress.ip_address("10.23.45.56") \ in ipaddress.ip_network("10.0.0.0/8") True

Slide 16

Slide 16 text

• /?a=fetch&content=die(@md5(HelloThinkCMF)) • /wp-content/plugins/google-document-embedder/libs/pdf.php? fn=lol.pdf&file=../../../../wp-config.php • /wp-admin/admin-ajax.php?action=kbslider_show_image&img=../ wp-config.php

Slide 17

Slide 17 text

YARL

Slide 18

Slide 18 text

YARL >>> u = yarl.URL("https://hynek.me/articles/")

Slide 19

Slide 19 text

YARL >>> u = yarl.URL("https://hynek.me/articles/") >>> u.host 'hynek.me' >>> u.path '/articles/'

Slide 20

Slide 20 text

YARL >>> u = yarl.URL("https://hynek.me/articles/") >>> u.host 'hynek.me' >>> u.path '/articles/' >>> u / "speaking/" URL('https://hynek.me/articles/speaking/')

Slide 21

Slide 21 text

YARL >>> u = yarl.URL("https://hynek.me/articles/") >>> u.host 'hynek.me' >>> u.path '/articles/' >>> u / "speaking/" URL('https://hynek.me/articles/speaking/') >>> u.with_path("about/") URL('https://hynek.me/about/')

Slide 22

Slide 22 text

>>> u = yarl.URL.build( scheme="redis", user="scott", password="tiger", host="redis.local", port=369, path="/1", query={"socket_timeout": 42}) >>> u URL('redis://scott:[email protected]:369/1?socket_timeout=42')

Slide 23

Slide 23 text

>>> u = yarl.URL.build( scheme="redis", user="scott", password="tiger", host="redis.local", port=369, path="/1", query={"socket_timeout": 42}) >>> u URL('redis://scott:[email protected]:369/1?socket_timeout=42') >>> redis.ConnectionPool.from_url(str(u))

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

def f(a=False, b=False, c=False): ... f(b=True)

Slide 26

Slide 26 text

def f(a=False, b=False, c=False): ... f(b=True) def f(what): ... f("b")

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

ENUM from enum import Enum class What(Enum): A = "a" B = "b" C = "c"

Slide 29

Slide 29 text

ENUM from enum import Enum class What(Enum): A = "a" B = "b" C = "c" f(What.A)

Slide 30

Slide 30 text

ENUM from enum import Enum class What(Enum): A = "a" B = "b" C = "c" def f(what: What): ... f(What.D) f(What.A)

Slide 31

Slide 31 text

ENUM from enum import Enum class What(Enum): A = "a" B = "b" C = "c" def f(what: What): ... f(What.D) f(What.A) error: "Type[What]" has no attribute "D"

Slide 32

Slide 32 text

@app.route("/") def view(): return { "foo": "bar" }

Slide 33

Slide 33 text

@app.route("/") def view(): return { "data": { "id": "some-id", "type": "example", "attributes": { "foo": "bar" } } "links": "http://localhost/", }

Slide 34

Slide 34 text

@bp.route("/", methods=["GET"]) def get_dns_record(id: int) -> APIResult: try: return APIResult( get_uow().dns_records.get(id) ) except UnknownDNSRecordError: raise_not_found("DNS record", id)

Slide 35

Slide 35 text

@bp.route("/", methods=["GET"]) def get_dns_record(id: int) -> APIResult: try: return APIResult( get_uow().dns_records.get(id) ) except UnknownDNSRecordError: raise_not_found("DNS record", id)

Slide 36

Slide 36 text

@bp.route("/", methods=["POST"]) @validated_body def create_dns_record(ndr: CreateDNSRecord) -> APIResult: try: dr_id = svc.create_record( get_uow(), ndr.domain, # ... ) except PlanError as e: raise APIError( id=error_ids.PLAN_NOT_SUFFICIENT, status="402", title=e.args[0], source={"pointer": "/data/attributes/domain"}, ) # ...

Slide 37

Slide 37 text

@bp.route("/", methods=["POST"]) @validated_body def create_dns_record(ndr: CreateDNSRecord) -> APIResult: try: dr_id = svc.create_record( get_uow(), ndr.domain, # ... ) except PlanError as e: raise APIError( id=error_ids.PLAN_NOT_SUFFICIENT, status="402", title=e.args[0], source={"pointer": "/data/attributes/domain"}, ) # ...

Slide 38

Slide 38 text

@bp.route("/", methods=["POST"]) @validated_body def create_dns_record(ndr: CreateDNSRecord) -> APIResult: try: dr_id = svc.create_record( get_uow(), ndr.domain, # ... ) except PlanError as e: raise APIError( id=error_ids.PLAN_NOT_SUFFICIENT, status="402", title=e.args[0], source={"pointer": "/data/attributes/domain"}, ) # ...

Slide 39

Slide 39 text

@bp.route("/", methods=["POST"]) @validated_body def create_dns_record(ndr: CreateDNSRecord) -> APIResult: try: dr_id = svc.create_record( get_uow(), ndr.domain, # ... ) except PlanError as e: raise APIError( id=error_ids.PLAN_NOT_SUFFICIENT, status="402", title=e.args[0], source={"pointer": "/data/attributes/domain"}, ) # ...

Slide 40

Slide 40 text

Locked Un- locked

Slide 41

Slide 41 text

Locked Un- locked Start

Slide 42

Slide 42 text

Locked Un- locked Insert Coin Start

Slide 43

Slide 43 text

Locked Un- locked Insert Coin Push Start

Slide 44

Slide 44 text

Locked Un- locked Insert Coin Push Insert Coin Start

Slide 45

Slide 45 text

Locked Un- locked Push Insert Coin Push Insert Coin Start

Slide 46

Slide 46 text

Classes

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

“Dunder” double underscores: •__init__ •__eq__ •...

Slide 52

Slide 52 text

class Point(namedtuple('Point', ['x', 'y'])): __slots__ = () @property def hypot(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def __str__(self): return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % ( self.x, self.y, self.hypot)

Slide 53

Slide 53 text

class Point(namedtuple('Point', ['x', 'y'])): __slots__ = () @property def hypot(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def __str__(self): return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % ( self.x, self.y, self.hypot) >>> Point.__mro__ (, , , )

Slide 54

Slide 54 text

CHARACTERISTIC @attributes( ["a"], defaults={"a": 42} ) class C: pass

Slide 55

Slide 55 text

@attr.s class Point: x = attr.ib() y = attr.ib() @property def hypot(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def __str__(self): return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % ( self.x, self.y, self.hypot)

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

Dataclasses

Slide 58

Slide 58 text

@dataclasses.dataclass class Point: x: int y: int @attr.dataclass class Point: x: int y: int

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

• 2.7

Slide 61

Slide 61 text

• 2.7 • __slots__

Slide 62

Slide 62 text

• 2.7 • __slots__ • types optional

Slide 63

Slide 63 text

• 2.7 • __slots__ • types optional • validators/converters

Slide 64

Slide 64 text

• 2.7 • __slots__ • types optional • validators/converters • free to innovate

Slide 65

Slide 65 text

from attrs import define, field @define class Point3D: x: int y: int z: int = field( validator=positive )

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

• embrace abstractions

Slide 68

Slide 68 text

• embrace abstractions • don’t be afraid of classes

Slide 69

Slide 69 text

• embrace abstractions • don’t be afraid of classes • wear your masks

Slide 70

Slide 70 text

ox.cx/a @hynek hynek.me vrmd.de