• Matthew Egan
• DiviPay
• Sydneysider
• mattjegan
• NullMatthew
• https://mattjegan.com
Any opinions conveyed in this talk are my own and not my employers
2
Slide 3
Slide 3 text
Thanks
• Adam Jacquier-Parr - www.github.com/aljp
• Christopher Di Bella - www.cjdb.com.au
• Daniel Kniaz & Russell Martin - www.divipay.com
3
Slide 4
Slide 4 text
Who is this for?
• Everyone who is comfortable with classes in Python
• I won’t be covering meta-classes in this talk
4
Slide 5
Slide 5 text
Why Descriptors?
• Descriptors are a feature of Python that is often overlooked
• Used primarily by library developers rather than application
developers
5
Slide 6
Slide 6 text
PSA: Use Python 3
• This talk uses Python 3.6+
• Python 2 is now at end of life and won’t be maintained after 2020
• Long live Python 3!
6
Slide 7
Slide 7 text
What?
• A problem
• Some solutions
• A better solution (hint: it’s descriptors)
7
Slide 8
Slide 8 text
Classes - A refresher
8
Slide 9
Slide 9 text
A Problem
• How can we make sure the name is always capitalized?
9
Slide 10
Slide 10 text
The current Person class: Our dream Person class:
10
Slide 11
Slide 11 text
__setattr__
• Is called whenever we try to set an instance variable
• Takes the calling object, the name of the attribute being set, and
the new value
11
Slide 12
Slide 12 text
__setattr__
12
Slide 13
Slide 13 text
13
Slide 14
Slide 14 text
__setattr__
• This does the job
• Locked to this class
• Gets out of hand with many properties
14
Slide 15
Slide 15 text
@property and @name.setter
15
Slide 16
Slide 16 text
16
Slide 17
Slide 17 text
@property and @name.setter
• This does the job
• Locked to this class
• Gets out of hand with
many properties
17
Slide 18
Slide 18 text
What about…
Simple Class Code + Reusable = Maintainable
18
Slide 19
Slide 19 text
Furthermore what about…
Simple Class Code + Reusable = Maintainable
19
Slide 20
Slide 20 text
The Descriptor Protocol
• Python exposes the descriptor protocol as a way to customize the
storing and retrieval of instance attributes
• Self-contained
• Reusable
20
Slide 21
Slide 21 text
The Descriptor Protocol
• __get__ is called when accessing the attribute
• __set__ is called when storing the attribute
• __delete__ is called when the attribute is being deleted
• __set_name__ is called once when the class object is created (Python
3.6+, PEP487)
21
A Solution
How do we solve our problem of capitalizing the name?
33
Slide 34
Slide 34 text
34
Slide 35
Slide 35 text
Use Cases
• Replicating customisation for multiple attrs without caring about
name
• Django generic foreign keys
• Validation
• Better error messages
35
Slide 36
Slide 36 text
Django Generic Foreign Keys
• Needs to store 2 values rather than 1
36