DevFox Labs
HomeCoursesRoadmapsChallengesToolsAboutContact
advanced35 minby DevFoxUpdated on 1 Aug 2026

Descriptors and Properties

What property is built from, the descriptor protocol underneath it, and using it deliberately for validation, laziness and computed attributes without turning a class into magic.

  • Python
Descriptors and Properties. Read this lesson at .

Previous lesson · 1 of 16The Data Model and Dunder MethodsNext lesson · 3 of 16Metaclasses and Class Creation

On this page

  • Property, first
  • What property actually is
  • Writing one
  • Where the value lives
  • Data and non-data descriptors
  • When not to
  • A cheat sheet to keep
  • Where to go next
DevFox Labs

Structured lessons and courses for developers who care about craft.

Platform

HomeCoursesRoadmapsAll lessonsChallengesAboutContactRSS feed

Legal

Terms of ServicePrivacy PolicyCookie Policy

© 2026 DevFox Labs. All rights reserved.

    @property turns a method into something that reads like an attribute. It is presented as syntax, and it is not — it is an ordinary class, written in a few lines of Python, implementing three methods you could implement yourself.

    Knowing that is worth more than knowing property, because the same mechanism explains how methods get bound to instances, how classmethod and staticmethod work, and how ORMs turn user.email into a database column. By the end of this lesson you will write descriptors, know where they store their data, and know the point at which one is more machinery than the problem deserves.

    Property, first

    python
    class Photo:
        def __init__(self, width: int, height: int) -> None:
            self._width = width
            self._height = height
    
        @property
        def aspect_ratio(self) -> float:
            return self._width / self._height
    python
    photo.aspect_ratio        # no parentheses - reads like a field

    The value is computed each time and never stored, so it cannot go stale. That is the main reason to use one: a derived value that would otherwise need updating whenever its inputs change.

    Adding a setter lets you validate on assignment:

    python
        @property
        def width(self) -> int:
            return self._width
    
        @width.setter
        def width(self, value: int) -> None:
            if value <= 0:
                raise ValueError(f"width must be positive, got {value}")
            self._width = value
    python
    photo.width = -5          # ValueError, at the assignment

    The important part is that callers write photo.width = 800. The validation arrived without changing a single call site, which is why you do not need getters and setters "just in case" — you can add them later without breaking anyone. That is the opposite of the convention in several other languages, and it is why Python code has public attributes.

    What property actually is

    A descriptor is any object defining __get__, __set__ or __delete__, used as a class attribute. Python's attribute lookup checks for these and calls them.

    Here is property, roughly, in enough detail to be honest:

    python
    class Property:
        def __init__(self, fget=None, fset=None):
            self.fget = fget
            self.fset = fset
    
        def __get__(self, instance, owner=None):
            if instance is None:
                return self                    # accessed on the class
            if self.fget is None:
                raise AttributeError("unreadable attribute")
            return self.fget(instance)
    
        def __set__(self, instance, value):
            if self.fset is None:
                raise AttributeError("can't set attribute")
            self.fset(instance, value)
    
        def setter(self, fset):
            return Property(self.fget, fset)

    That is the whole trick. @property puts an instance of this class in the class body; reading photo.width finds it and calls __get__.

    The instance is None branch is why Photo.width gives you the property object rather than an error — accessed on the class, there is no instance to compute from.

    Methods are descriptors too

    Functions define get. When you write photo.resize, the function's get returns a bound method — a small object holding the function and the instance — which is precisely why self arrives as the first argument without you passing it. staticmethod and classmethod are descriptors that bind differently. The mechanism you are learning is not an add-on; it is how methods work.

    Writing one

    The reason to reach past property is reuse. Five fields needing the same validation means five near-identical property pairs; a descriptor is written once.

    Three fields, one implementation, and the error message names the field — which comes from __set_name__, called by Python when the class is created, telling each descriptor what it was assigned to. Before that method existed you had to repeat the name (width = Positive("width")), and you will still see that in older code.

    Where the value lives

    The question every descriptor has to answer, and the one that produces the classic bug.

    Bad — storing the value on the descriptor.

    Good — storing it on the instance.

    There is one descriptor object per class attribute, shared by every instance — it is created once, in the class body. So the first version gives every Photo the same width: setting it on one changes it for all of them, and nothing errors. It is the mutable-class-attribute trap from the foundations course, in the one place where the sharing is not visible in the code.

    Storing in instance.__dict__ under the attribute's own name works because a descriptor defining __set__ takes priority over the instance dictionary during lookup — so the entry is findable by you and invisible to normal attribute access.

    Data and non-data descriptors

    That priority is a rule worth knowing precisely, because it explains behaviour that otherwise looks inconsistent.

    A data descriptor

    Defines __set__ or __delete__.

    Consulted before the instance __dict__, so nothing an instance stores can get around it. A property is one of these.

    A non-data descriptor

    Defines only __get__.

    Consulted after the instance __dict__, so assigning to the instance shadows it. Ordinary methods are these.

    One method's presence decides whether an instance attribute can shadow it

    Which gives the full lookup order:

    1. 1

      Data descriptors on the type

      They win over everything.

    2. 2

      The instance __dict__

    3. 3

      Non-data descriptors on the type

    4. 4

      Class attributes

    5. 5

      __getattr__, if nothing was found

    Every surprising attribute-access behaviour in Python is one of these five steps firing before you expected

    So a property (data) cannot be shadowed by setting an instance attribute, and a plain method (non-data) can:

    This is also how functools.cached_property works: it is a non-data descriptor, so on first access it computes the value and writes it into instance.__dict__, and every later access finds the instance entry at step 2 without the descriptor running at all.

    When not to

    Descriptors are the mechanism behind ORMs, validation frameworks and typed settings libraries. They are almost always the wrong answer in application code.

    Prefer, in this order:

    1. 1

      A plain attribute

      Most values need nothing at all.

    2. 2

      A dataclass with __post_init__

      Validation in one place, at construction, which the modelling lesson argued is where it belongs.

    3. 3

      A property

      For one computed or validated field.

    4. 4

      A descriptor

      Only when the same behaviour repeats across several fields or several classes, and you own both sides.

    Only reach for the next one when the one before it has actually failed you

    The costs are real: attribute access is no longer obvious to a reader, type checkers need care to follow it, and debugging goes through machinery in another file. A descriptor used three times in one class earns its place; one used once is a property written the long way.

    __slots__ leaves a descriptor nowhere to go

    A class with slots stores attributes in slot descriptors rather than in instance.dict — so a custom descriptor that writes to instance.dict raises AttributeError, because there is no dictionary. Either drop slots or have the descriptor store under a different private slot name.

    A cheat sheet to keep

    Where to go next

    You now know that property is not syntax, where a descriptor must put its data, and the lookup order that decides which attribute wins. That order is the thing to keep — it explains cached_property, bound methods, and why some attributes can be shadowed and others cannot.

    Next is Metaclasses and Class Creation, which goes one level further out. Descriptors customise what happens when an attribute is accessed; metaclasses customise what happens when a class is created — and the lesson spends much of its length on the two simpler tools that solve most of what people reach for metaclasses to do.

    Before you move on, write the Positive descriptor and use it on two fields of one class. Then deliberately store the value on the descriptor instead of the instance, create two objects, and watch them share a value. That failure takes thirty seconds to produce and is the single thing worth remembering from this lesson.

    text
    PROPERTY
      @property                 computed, never stale
      @x.setter                 validate on assignment
      callers still write obj.x = 5 - no call sites change
      which is why Python has public attributes and no
      defensive getters
    
    WHAT IT IS
      a descriptor: an object defining __get__/__set__/__delete__,
      used as a CLASS attribute
      property is ~20 lines of ordinary Python
      functions are descriptors too - that is how self gets bound
    
    WRITING ONE
      def __set_name__(self, owner, name)   Python tells you the name
      def __get__(self, instance, owner=None)
          if instance is None: return self   accessed on the class
      def __set__(self, instance, value)
    
    STORAGE - the classic bug
      ONE descriptor object per class attribute, shared by all
      instances
      storing on self  -> every instance shares one value, silently
      store in instance.__dict__[self._name]
    
    LOOKUP ORDER
      1 data descriptors (__set__/__delete__)   <- beat the instance
      2 instance __dict__
      3 non-data descriptors (__get__ only)
      4 class attributes
      5 __getattr__
    
      property cannot be shadowed; a method can
      cached_property is non-data: it writes to __dict__ once,
      then step 2 answers forever
    
    WHEN
      plain attribute > dataclass __post_init__ > property > descriptor
      a descriptor earns its place when the behaviour REPEATS
    
    TRAP
      __slots__ means no instance __dict__ to write into
    python
    class Positive:
        """A numeric attribute that must be greater than zero."""
    
        def __set_name__(self, owner: type, name: str) -> None:
            self._name = name                  # the attribute's own name
    
        def __get__(self, instance, owner=None):
            if instance is None:
                return self
            return instance.__dict__[self._name]
    
        def __set__(self, instance, value) -> None:
            if value <= 0:
                raise ValueError(
                    f"{self._name} must be positive, got {value!r}"
                )
            instance.__dict__[self._name] = value
    python
    class Photo:
        width = Positive()
        height = Positive()
        file_size = Positive()
    
        def __init__(self, width, height, file_size):
            self.width = width          # goes through __set__
            self.height = height
            self.file_size = file_size
    python
    Photo(800, 600, -1)
    # ValueError: file_size must be positive, got -1
    python
    class Positive:
        def __set__(self, instance, value):
            self._value = value            # on the DESCRIPTOR
    
        def __get__(self, instance, owner=None):
            return self._value
    python
    class Positive:
        def __set_name__(self, owner, name):
            self._name = name
    
        def __set__(self, instance, value):
            instance.__dict__[self._name] = value
    
        def __get__(self, instance, owner=None):
            if instance is None:
                return self
            return instance.__dict__[self._name]
    python
    photo.resize = lambda: None      # shadows the method, no error
    photo.width = 800                # goes through the property