Demystifying Python’s Descriptor Protocol: The Magic Behind Properties and Methods

Elshad Karimov
4 min readJust now
Photo by Meritt Thomas on Unsplash

Python is a language filled with magic, and one of its lesser-known but incredibly powerful features is the descriptor protocol. While you may not have heard of it by name, descriptors are the foundation for many familiar Python features, such as properties, methods, static methods, class methods, and more. If you’ve ever used @property or defined a method in a class, you've interacted with descriptors. Let’s pull back the curtain and explore this fascinating topic.

What Are Descriptors?

A descriptor is any Python object that implements one or more of the following methods:

  1. __get__(self, instance, owner): Defines behavior when the attribute is accessed.
  2. __set__(self, instance, value): Defines behavior when the attribute is assigned.
  3. __delete__(self, instance): Defines behavior when the attribute is deleted.

Descriptors are invoked automatically by Python’s attribute access mechanisms. They allow you to customize how attributes of a class are accessed and modified.

The Basics of Descriptors

Let’s start with a simple descriptor that logs when an attribute is accessed:

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet