Skip to the solution
HardDSA10 min read

What is the descriptor protocol?

340 views

The problem

Question presented to candidate: "What is the descriptor protocol in Python? Explain __get__, __set__ and __set_name__, the difference between a data and a non-data descriptor, and show me a case where you would write one yourself."

What a strong answer should cover:

  • A descriptor is an object stored as a class attribute whose type defines __get__(self, obj, objtype), and optionally __set__(self, obj, value) / __delete__(self, obj); attribute access through an instance then calls those methods.
  • Data descriptor (has __set__ or __delete__) beats the instance __dict__; non-data descriptor (only __get__) loses to it β€” and why that matters for caching.
  • __get__ receives obj=None when accessed on the class, and conventionally returns the descriptor itself; __set_name__(owner, name) (Python 3.6, PEP 487) tells the descriptor the attribute name it was assigned to.
  • Built-ins are descriptors: functions (binding self into a bound method), property, classmethod, staticmethod, __slots__ members, functools.cached_property.
  • Typical uses: validated or typed fields, ORM columns, lazy/cached attributes; per-instance data must live on the instance (e.g. its __dict__), not on the shared descriptor.

Code / implementation expected: Yes β€” a small validating descriptor (for example a Positive field) using __set_name__, __get__ and __set__.

  • descriptors
  • data-model

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA validated field descriptor with __set_name__
PythonMethods, property, classmethod and a lazy cached attribute

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 134 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

What is __init_subclass__ in Python?

Continue