SlideShare a Scribd company logo
amitu.com
Descriptors In
Python
Excerpt from Python For Programmers
available on amitu.com/python/
amitu.com Descriptors In Python
This is an excerpt of my upcoming python book
amitu.com/python/
amitu.com Descriptors In Python
Lets take a look at property in Python
amitu.com Descriptors In Python
Or with a @property syntax sugar
amitu.com Descriptors In Python
So what exactly is the property() returning?
amitu.com Descriptors In Python
And why don't we get what property() returns
when we access .first_name?
student.first_name appears to be simple
string object!
amitu.com Descriptors In Python
And assigning to a property is even weirder.
It doesn't seem to be overwriting anything,
as normally assignment does.
It calls a function! The setter.
What were you smoking Guido?!?
amitu.com Descriptors In Python
We know that properties are useful, no
complaints here.
The real question is…
… is this some compiler/interpreter magic?
or
is it application of some simple feature
available to us?
amitu.com Descriptors In Python
We know the @ syntax is just a syntax
sugar, we love it, we create decorators
using them.
Out of @property()…
Which leaves us with property()
function or decorator.
Is property() special, or can we write it ourselves?
amitu.com Descriptors In Python
… and the answer is YES!
The name of the feature is descriptor.
Django’s ORM uses it extensively
for example…
amitu.com Descriptors In Python
Lets recap what happens when Python sees
attribute access:
[of course we are simplifying thins, no __mro__, no
__call__ etc etc]
amitu.com Descriptors In Python
… but the picture is closer to:
(we are reusing the function defined in previous slide)
amitu.com Descriptors In Python
… or in English:
If on an object, say o, when you do an attribute
lookup, say o.x, if Python finds an object at o.x
that has o.x.__get__ attribute, then instead of
returning o.x, it returns whatever
o.x.__get__(o, o.__class__) returns.
amitu.com Descriptors In Python
… when doing setting an attribute, (o.x = 10),
o.x__set__(o, 10) is looked up and called …
And this is not only for reading an attribute…
… and when you call del o.x,
o.x.__delete__(obj, o.__class__) is called if
present.
amitu.com Descriptors In Python
With that in mind, lets implement @property:
Doesn’t look that hard, does it?
amitu.com Descriptors In Python
Lets use our MyProperty:
Works like a charm!
amitu.com Descriptors In Python
When better_lookup() sees .first_name, it
finds instance of our class, and our class
instances do have .__get__(), so Python calls
it, which calls ._getter(), that was passed to
MyProperty() constructor (.__init__())
because we used it as a decorator!
amitu.com Descriptors In Python
Please note:
MyProperty class instance is created when
Student class is being constructed (as against
when student instance is being initialised).
amitu.com Descriptors In Python
Lets try setter:
amitu.com Descriptors In Python
Using the setter:
amitu.com Descriptors In Python
How we implemented @name.setter is by
realising that name now points to an
instance of our MyProperty class, and that
instance happened to have .setter()
method, which happens to take a function
as argument, so name.setter can be used
as a decorator too.
amitu.com Descriptors In Python
Cool, so we can implement @property
using descriptors.
Next question is:
When to use descriptor over property?
amitu.com Descriptors In Python
The deciding factor:
The implementation of the property lives
inside the class that is using the property.
The descriptor on the other hand is a
separate class altogether.
Let me clarify…
amitu.com Descriptors In Python
Say we want to implement .name on a
bunch of classes.
1. It must convert assigned names to
UPPER case.
2. It must validate that name is composed
of two words.
3. Name must be maximum of 100 chars
long.
amitu.com Descriptors In Python
Say we want .name on Student, Parent and
Teacher classes, and they have nothing else
in common.
amitu.com Descriptors In Python
One solution is we implement a NamedObject,
and subclass each of Student, Parent and
Teacher from NamedObject:
and so on for Parent and Teacher
amitu.com Descriptors In Python
The property based solution works, but it
does not “scale”.
What if we don't just have .name, but
also .spouse_name on Student?
What if along with .name
and .spouse_name, we also want different
length validations on each name, .name
must be 100 chars, but .spouse_name upto
80 chars?
amitu.com Descriptors In Python
A property based solution would
require us to keep track
of ._name, ._spouse_name, ._nam
e_length and ._spouse_length on
Student object.
amitu.com Descriptors In Python
Lets see how to implemented this using descriptors?
amitu.com Descriptors In Python
As you can see descriptor scales pretty well,
encapsulates better.
We can even subclass Name descriptor to add
more features to it, and we wont have to touch
the Student class etc.
amitu.com Descriptors In Python
A note on descriptors as class attributes:
If we try to access a descriptor using the class instead
of instance, e.g. Student.name instead of
student.name (where student = Student()), .__get__()
is still called with obj set to None.
amitu.com Descriptors In Python
… and at class level .__set__()
and .__delete__() calls are not allowed.
amitu.com Descriptors In Python
Thats it for now!
You have seen a section in my Python for
Developers book. This covers python
material for people who're already
developers, even python developers.
Check it out: amitu.com/python/

More Related Content

PDF
Function in Python
PDF
R P G Generator
PDF
Sql server difference faqs- 9
PPTX
Code Like Pythonista
PPTX
Build a compiler using C#, Irony and RunSharp.
PDF
Function arguments In Python
PPSX
python Function
Function in Python
R P G Generator
Sql server difference faqs- 9
Code Like Pythonista
Build a compiler using C#, Irony and RunSharp.
Function arguments In Python
python Function

Viewers also liked (8)

PDF
Lazy evaluation in Python
PDF
Python testing-frameworks overview
PDF
Ansible loves Python, Python Philadelphia meetup
PPTX
Advance OOP concepts in Python
PDF
Generators: The Final Frontier
PDF
Mastering Python 3 I/O (Version 2)
PDF
An Introduction to Python Concurrency
PDF
Visual Design with Data
Lazy evaluation in Python
Python testing-frameworks overview
Ansible loves Python, Python Philadelphia meetup
Advance OOP concepts in Python
Generators: The Final Frontier
Mastering Python 3 I/O (Version 2)
An Introduction to Python Concurrency
Visual Design with Data
Ad

Similar to Descriptors In Python (20)

PDF
Python+Deep+Dive+1(Python Course ).pdf
PPTX
Module-5-Classes and Objects for Python Programming.pptx
PPTX
Python OOPs
PDF
Anton Kasyanov, Introduction to Python, Lecture2
PPTX
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
PPTX
Learn about Python power point presentation
PPTX
Chapter 05 classes and objects
PDF
MacAD.UK 2018: Your Code Should Document Itself
PDF
Python Advanced Course - part I.pdf for Python
PPT
Basics of Programming_Python__Lecture__3.ppt
PPTX
UNIT-5 object oriented programming lecture
PPT
Writing Apps the Google-y Way
PDF
Python cheat-sheet
PPT
Programming with _Python__Lecture__3.ppt
PDF
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
ODP
Dynamic Python
PPTX
Python programming computer science and engineering
PPTX
unit (1)INTRODUCTION TO PYTHON course.pptx
PDF
Python_Unit_2.pdf
PPTX
Java Tips, Tricks and Pitfalls
Python+Deep+Dive+1(Python Course ).pdf
Module-5-Classes and Objects for Python Programming.pptx
Python OOPs
Anton Kasyanov, Introduction to Python, Lecture2
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
Learn about Python power point presentation
Chapter 05 classes and objects
MacAD.UK 2018: Your Code Should Document Itself
Python Advanced Course - part I.pdf for Python
Basics of Programming_Python__Lecture__3.ppt
UNIT-5 object oriented programming lecture
Writing Apps the Google-y Way
Python cheat-sheet
Programming with _Python__Lecture__3.ppt
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Dynamic Python
Python programming computer science and engineering
unit (1)INTRODUCTION TO PYTHON course.pptx
Python_Unit_2.pdf
Java Tips, Tricks and Pitfalls
Ad

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Cloud computing and distributed systems.
PDF
Machine learning based COVID-19 study performance prediction
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
The AUB Centre for AI in Media Proposal.docx
Advanced methodologies resolving dimensionality complications for autism neur...
Network Security Unit 5.pdf for BCA BBA.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Diabetes mellitus diagnosis method based random forest with bat algorithm
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Programs and apps: productivity, graphics, security and other tools
Cloud computing and distributed systems.
Machine learning based COVID-19 study performance prediction
20250228 LYD VKU AI Blended-Learning.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf

Descriptors In Python

  • 1. amitu.com Descriptors In Python Excerpt from Python For Programmers available on amitu.com/python/
  • 2. amitu.com Descriptors In Python This is an excerpt of my upcoming python book amitu.com/python/
  • 3. amitu.com Descriptors In Python Lets take a look at property in Python
  • 4. amitu.com Descriptors In Python Or with a @property syntax sugar
  • 5. amitu.com Descriptors In Python So what exactly is the property() returning?
  • 6. amitu.com Descriptors In Python And why don't we get what property() returns when we access .first_name? student.first_name appears to be simple string object!
  • 7. amitu.com Descriptors In Python And assigning to a property is even weirder. It doesn't seem to be overwriting anything, as normally assignment does. It calls a function! The setter. What were you smoking Guido?!?
  • 8. amitu.com Descriptors In Python We know that properties are useful, no complaints here. The real question is… … is this some compiler/interpreter magic? or is it application of some simple feature available to us?
  • 9. amitu.com Descriptors In Python We know the @ syntax is just a syntax sugar, we love it, we create decorators using them. Out of @property()… Which leaves us with property() function or decorator. Is property() special, or can we write it ourselves?
  • 10. amitu.com Descriptors In Python … and the answer is YES! The name of the feature is descriptor. Django’s ORM uses it extensively for example…
  • 11. amitu.com Descriptors In Python Lets recap what happens when Python sees attribute access: [of course we are simplifying thins, no __mro__, no __call__ etc etc]
  • 12. amitu.com Descriptors In Python … but the picture is closer to: (we are reusing the function defined in previous slide)
  • 13. amitu.com Descriptors In Python … or in English: If on an object, say o, when you do an attribute lookup, say o.x, if Python finds an object at o.x that has o.x.__get__ attribute, then instead of returning o.x, it returns whatever o.x.__get__(o, o.__class__) returns.
  • 14. amitu.com Descriptors In Python … when doing setting an attribute, (o.x = 10), o.x__set__(o, 10) is looked up and called … And this is not only for reading an attribute… … and when you call del o.x, o.x.__delete__(obj, o.__class__) is called if present.
  • 15. amitu.com Descriptors In Python With that in mind, lets implement @property: Doesn’t look that hard, does it?
  • 16. amitu.com Descriptors In Python Lets use our MyProperty: Works like a charm!
  • 17. amitu.com Descriptors In Python When better_lookup() sees .first_name, it finds instance of our class, and our class instances do have .__get__(), so Python calls it, which calls ._getter(), that was passed to MyProperty() constructor (.__init__()) because we used it as a decorator!
  • 18. amitu.com Descriptors In Python Please note: MyProperty class instance is created when Student class is being constructed (as against when student instance is being initialised).
  • 19. amitu.com Descriptors In Python Lets try setter:
  • 20. amitu.com Descriptors In Python Using the setter:
  • 21. amitu.com Descriptors In Python How we implemented @name.setter is by realising that name now points to an instance of our MyProperty class, and that instance happened to have .setter() method, which happens to take a function as argument, so name.setter can be used as a decorator too.
  • 22. amitu.com Descriptors In Python Cool, so we can implement @property using descriptors. Next question is: When to use descriptor over property?
  • 23. amitu.com Descriptors In Python The deciding factor: The implementation of the property lives inside the class that is using the property. The descriptor on the other hand is a separate class altogether. Let me clarify…
  • 24. amitu.com Descriptors In Python Say we want to implement .name on a bunch of classes. 1. It must convert assigned names to UPPER case. 2. It must validate that name is composed of two words. 3. Name must be maximum of 100 chars long.
  • 25. amitu.com Descriptors In Python Say we want .name on Student, Parent and Teacher classes, and they have nothing else in common.
  • 26. amitu.com Descriptors In Python One solution is we implement a NamedObject, and subclass each of Student, Parent and Teacher from NamedObject: and so on for Parent and Teacher
  • 27. amitu.com Descriptors In Python The property based solution works, but it does not “scale”. What if we don't just have .name, but also .spouse_name on Student? What if along with .name and .spouse_name, we also want different length validations on each name, .name must be 100 chars, but .spouse_name upto 80 chars?
  • 28. amitu.com Descriptors In Python A property based solution would require us to keep track of ._name, ._spouse_name, ._nam e_length and ._spouse_length on Student object.
  • 29. amitu.com Descriptors In Python Lets see how to implemented this using descriptors?
  • 30. amitu.com Descriptors In Python As you can see descriptor scales pretty well, encapsulates better. We can even subclass Name descriptor to add more features to it, and we wont have to touch the Student class etc.
  • 31. amitu.com Descriptors In Python A note on descriptors as class attributes: If we try to access a descriptor using the class instead of instance, e.g. Student.name instead of student.name (where student = Student()), .__get__() is still called with obj set to None.
  • 32. amitu.com Descriptors In Python … and at class level .__set__() and .__delete__() calls are not allowed.
  • 33. amitu.com Descriptors In Python Thats it for now! You have seen a section in my Python for Developers book. This covers python material for people who're already developers, even python developers. Check it out: amitu.com/python/