Advertisement

Descriptors & Properties interview questions and answers

15 Descriptors & Properties interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How would you write a descriptor supporting attribute DELETION via __delete__, and what real use case does that enable?

Implement __delete__(self, instance) to run custom logic when 'del instance.attr' is called — useful for cleanup actions (like closing a resource, invalidating a related cache, or resetting to a default) that should happen specifically when an attribute is explicitly removed rather than just reassigned.
class ManagedResource:
    def __set_name__(self, owner, name):
        self.name = f"_{name}"
    def __get__(self, instance, owner):
        return getattr(instance, self.name, None)
    def __set__(self, instance, value):
        setattr(instance, self.name, value)
    def __delete__(self, instance):
        resource = getattr(instance, self.name, None)
        if resource:
            resource.close()  # cleanup runs specifically on 'del'
        delattr(instance, self.name)
Real-world example
Ensuring a resource (like a file handle stored on an object) is properly released when its attribute is explicitly deleted with 'del'.
Likely follow-ups
  • How does this differ in behavior and trigger conditions from cleanup logic placed in a class's __del__ method instead?
File I/O & Context Managers
Q12 Advanced Save

How do properties and descriptors interact with __slots__, and what special consideration is needed?

A descriptor (including @property) works fine as a CLASS attribute alongside __slots__, since the descriptor ITSELF lives on the class, not the instance — but a custom descriptor's __get__/__set__ implementation CAN'T use a plain instance.__dict__ for storage (since __slots__ removes __dict__ entirely) and must instead store data in a DEDICATED slot or a WeakKeyDictionary keyed by instance.
class Point:
    __slots__ = ("_x",)  # explicit slot for internal storage
    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, value):
        self._x = value  # stored in the '_x' slot, not a __dict__ (which doesn't exist)

p = Point()
p.x = 5
print(p.x)  # 5
Real-world example
Combining @property-based validation with __slots__-based memory optimization for a class expected to have millions of instances.
Likely follow-ups
  • How would a generic, reusable descriptor (not using @property) need to store per-instance data when the class uses __slots__?
Data Types & Structures
Q13 Advanced Save

How would you use a WeakKeyDictionary inside a descriptor to store per-instance data without relying on the instance's own __dict__ or requiring a dedicated __slots__ entry?

Store {instance: value} pairs in a weakref.WeakKeyDictionary INSIDE the descriptor object itself (not the instance) — WeakKeyDictionary automatically removes entries once the corresponding instance is garbage collected, avoiding both the __slots__ storage problem AND any risk of the descriptor's cache keeping instances alive forever (a memory leak).
import weakref

class Cached:
    def __init__(self):
        self.data = weakref.WeakKeyDictionary()
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self.data.get(instance)
    def __set__(self, instance, value):
        self.data[instance] = value
Real-world example
Building a descriptor that works correctly even on classes using __slots__, without leaking memory by keeping instances alive indefinitely.
Likely follow-ups
  • Why is a REGULAR dictionary (not WeakKeyDictionary) risky to use for this same purpose, in terms of memory leaks?
Memory Management & Garbage Collection
Q14 Advanced Save

How does @property's read-only behavior (no setter defined) actually raise an AttributeError, and how would you customize that error message?

If only a getter is defined (no @x.setter), attempting to ASSIGN to the property raises `AttributeError: can't set attribute` by default; to provide a more descriptive custom message, explicitly define a setter that always raises your own AttributeError with a clearer explanation.
class ReadOnly:
    @property
    def value(self):
        return 42
    @value.setter
    def value(self, new_value):
        raise AttributeError("'value' is read-only and cannot be modified after creation")

r = ReadOnly()
# r.value = 99  # AttributeError: 'value' is read-only and cannot be modified after creation
Real-world example
Providing a clearer, more helpful error message when code mistakenly tries to set a computed, read-only property.
Likely follow-ups
  • Is there a performance or design reason to prefer the default terse error over writing this more descriptive custom one?
Exception Handling
Q15 Beginner Save

How would you convert an existing plain attribute into a property later, without breaking any existing code that reads or writes it directly?

Since attribute access syntax (obj.attr) looks identical whether it's a plain instance attribute or a property, you can freely replace a plain attribute with an @property (backed by a renamed private attribute) at any time without changing any external code that reads or assigns to it — this is a key reason Python developers don't need to write getters/setters defensively upfront.
# Before: plain attribute
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

# After: converted to a property, external code (t.celsius) is unaffected
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def celsius(self):
        return self._celsius
    @celsius.setter
    def celsius(self, value):
        self._celsius = value
Real-world example
Adding validation to a class's attribute later in a project's life, without needing to update every place that already reads or writes that attribute.
Likely follow-ups
  • Why is this seamless upgrade path considered a key advantage of Python's approach compared to languages that require explicit getters/setters from the start?
OOP

Showing 11–15 of 15