Writing Classes#

Class Naming#

Class names must use CapWords (e.g., MyClass), in line with widely accepted Python conventions and PEP 8 guidelines.

We are deliberately not using the Base prefix. Classes are named to reflect the object they model, and extended (if need be) via inheritance using progressively specific names using meaningful prefixes rather than just Base — for example, Variation as the parent class and StructuralVariation as its subclass.

Rationale: This is a matter of stylistic preference — both approaches offer the same extensibility.

Class attributes#

Non-derived attributes#

Attributes that are not derived from other attributes are defined in the class body with type annotations. They are generally not lazy-loaded or cached and further categorised into core attributes and externally-set attributes.

Core Attributes#

Core attributes are those that are set during object initialization and are essential to the object’s identity. They are included in the __init__ method generated by attrs. They do not have default values.

from ensembl.vep.common import UnsafeSetterMixin, invalidates
class MyClass(UnsafeSetterMixin):
    core_attr1: int = field(on_setattr=invalidates('derived_attr1'))
    core_attr2: str
    derived_attr1: int = field(init=False)

    def some_method(self):
        derived_attr1 = self.core_attr1 * 2

cls = MyClass(core_attr1=1, core_attr2="foo")
with cls.unsafe():
    cls.core_attr1 = 2

Externally-set attributes#

These are similarly not derived and externally set like core attributes but they are not essential to be in the __init__ method. The class is not responsible for calculating these attributes, so it should not enforce immutability or caching.

They should still be defined in the class body (with type annotations) to be compatible with slots=True and to ensure they are tracked properly.

class MyClass():
    core_attr: int
    externally_set_attr: int = field(init=False)

cls = MyClass(core_attr=1)
cls.externally_set_attr = some_external_method()

Derived Attributes#

Derived attributes are read-only properties derived from one or more attributes. They are lazy-loaded (not part of __init__) and can be cached (using functools.cached_property).

Read-only enforcement is handled by the using a combination of a protected variable (prefixing name with _) and a public variable property with no setter. The public variable should be used for all access outside of the class definition, the protected variable is for internal use only. Because the public accessible variable has no setter, you should never assign directly to it, mypy will throw a misc error if you do (property is read-only). Reading or assigning to the protected variable directly outside of the class definition will result in a W202 error by pylint. Both will fail the CI checks and should be avoided. Ensure mypy and pylint are enabled in your IDE for linting annotations during development.

Lazy-loading is achieved by setting init=False for the derived attribute, which means it will not be included in the __init__ method and will only be computed when accessed.

Caching is implemented using functools.cached_property on the private variable, which stores the computed value after the first access and returns the cached value on subsequent accesses. In some cases, the derived attribute may not be cached,

  • if the computation is cheap and does not justify the overhead of caching, or

  • if the derived attribute is set by product of some internal computation and does not have its own function to be decorated with @cached_property.

class MyClass(CachedAttributeGuardMixin):
    core_attr1: int
    _derived_attr3: int = field(init=False, default=0)    # default value for non-cached derived attribute that is set by internal computation

    @property
    def derived_attr1(self) -> int:
        return self._derived_attr1

    @cached_property
    def _derived_attr1(self) -> int:
        # perform expensive computation here using core_attr1
        return sum(range(self.core_attr1 * 2))

    @property
    def derived_attr2(self) -> int:
        # perform cheap computation here using core_attr1
        # does not justify caching
        return self.core_attr1 + 1

    @property
    def derived_attr3(self) -> int:
        # this attribute is set by some internal computation
        return self._derived_attr3

    @cached_property
    def _derived_attr3(self) -> int:
        # alternative to defining default value at attribute definition
        # can be used for some minor compuations for initial value assignment
        return 0

    def some_internal_computation(self):
        # perform some internal computation here and set derived_attr3
        # cannot do caching
        self._derived_attr3 = self.core_attr1 * 2

Cache invalidation#

It is expected that core attributes are not changed after initialization. In the unlikely event they do need to be updated, the related derived attributes needs to be invalidated. Some derived attribute may also depend on other derived attributes, we may need to invalidate those as well.

Invalidating cache dependent on core attributes: This is handled by using the invalidates hook with on_setattr. This has speed penalty for object creation and assignment of core attributes. Core attributes are not expected to be updated that much.

class MyClass:
    core_attr1: int = field(on_setattr=invalidates('_derived_attr1'))
    
    @property
    def derived_attr1(self) -> int:
        return self._derived_attr1

    @cached_property
    def _derived_attr1(self) -> int:
        # perform expensive computation here using core_attr1
        return sum(range(self.core_attr1 * 2))

Invalidating cache dependent on derived attributes: Derived attributes may not be defined in the attribute list, so we cannot use invalidates hook. Instead, we can directly call invalidate function from the function that calculates the derived attribute that the other derived attribute depends on.

class MyClass():
    core_attr1: int

    @property
    def derived_attr1(self) -> int:
        return self._derived_attr1

    @cached_property
    def _derived_attr1(self) -> int:
        invalidate(self, '_derived_attr2')  # invalidate dependent derived attribute

        # perform expensive computation here using core_attr1
        return sum(range(self.core_attr1 * 2))

    @property
    def derived_attr2(self) -> int:
        return self._derived_attr2

    @cached_property
    def _derived_attr2(self) -> int:
        # perform expensive computation here using derived_attr1
        return self.derived_attr1 + 1

Resetting derived attribute which does not have its own function: In some cases, the derived attribute is set by some internal computation and does not have its own function to be decorated with @cached_property (third case mentioned in Derived Attributes). So, if we invalidate the attribute and in some place we try to access it, we will run into error. In such cases, we can use reset_attrs that will instead of invalidating the attribute, reset it to its default state.

Note: In some cases, we may want to allow updating core attributes without invalidating derived attributes. In that case, we can also use the UnsafeSetterMixin mixin. It allows using context managers to temporarily disable cache invalidation for faster but unsafe attribute update. Generally this should not be necessary.

class MyClass(UnsafeSetterMixin):
    core_attr1: int = field(on_setattr=invalidates('_derived_attr1'))
    
    @property
    def derived_attr1(self) -> int:
        return self._derived_attr1

    @cached_property
    def _derived_attr1(self) -> int:
        # perform expensive computation here using core_attr1
        return sum(range(self.core_attr1 * 2))

cls = MyClass(core_attr1=1)
with cls.unsafe():
    cls.core_attr1 = 2  # does not invalidate derived_attr1

Assigning attributes without running hooks: When building a brand-new object, before construction is complete and before anything has read a value derived from the field being set, we may want to assign to attributes without running any hooks. The assign_without_hooks method can be used to set the real field and avoid running not just any on_setattr hooks, but also any validators or converters that attrs would normally run, and consequently speed up assigning those values.

For example, when creating a Transcript object, we can immediately assign the spliced_exons attribute, because none of the downstream attributes have been cached yet, so there is nothing to invalidate. We can avoid numerous method calls and speed up attribute assignment.

transcript = Transcript(
    stable_id=group.transcript_id,
    start=transcript_record.start,
    end=transcript_record.end,
    strand=strand,
    slice=genomic_slice,
)
transcript.assign_without_hooks(spliced_exons=exons)

Use of attrs#

We heavily use the attrs module for writing classes. All classes use the following attrs decorator defaults:

slots = True

Slotted classes are enabled by default for improved memory efficiency and attribute access performance.

Caveat: Slotted classes come with known limitations. Refer to the attrs glossary on slotted classes for a full list.

Rationale: This is an intentional design constraint. Requiring all attributes to be declared upfront — including private or cache-related ones — prevents hidden state from accumulating across the codebase. Readers should be able to understand an object’s full structure without hunting through unrelated code paths.

auto_attribs = True

All attributes must have explicit type annotations. This is enforced to maintain consistency and enable static analysis.

kw_only = True

All constructor arguments are keyword-only. This improves readability at call sites by making argument names self-documenting.

# Good — intent is clear
MyClass(name="foo", value=42)

# Avoided — positional args obscure intent
MyClass("foo", 42)

on_setattr vs Custom __setattr__

We use a custom __setattr__ rather than on_setattr because on_setattr does not trigger for attributes defined via @cached_property — even at the class level. Since we want these cached attributes to be immutable and they cannot be registered in the attrs attribute list, a custom __setattr__ is necessary to enforce that constraint uniformly.

Caveat: This approach may cause performance issues. As setattr is called for every attribute assignment, it can introduce overhead, especially if there are many attributes or frequent updates. This is a trade-off between enforcing immutability and performance.

We can possibly emulate the attrs-generated __setattr__ if required in future -

def __setattr__(self, name, val):
    try:
        a, hook = sa_attrs[name]
    except KeyError:
        nval = val
    else:
        nval = hook(self, a, val)

    _OBJ_SETATTR(self, name, nval)

This uses a dictionary lookup (sa_attrs) to resolve any validation or conversion hooks, falling back to a plain assignment if the attribute is not registered.

Open questions:

  • Can __setattr__ be further optimised and eliminate loops and conditionals?

  • Is there a way to register @cached_property attributes in the attrs attribute list so that they are handled by on_setattr?

  • Is it better to implement custom caching logic with immutability instead of setattr?

More Open Questions

  • match_args — Should this be explicitly set?

  • collect_by_mro — Should this be explicitly set?

Multiple Inheritance#

Inheritance and Mixins#

Since we use slots=True, multiple inheritance is not straightforward — attrs requires that only one of the parent classes can use slots=True. And, if you inherit from class that is not using slots then you lose some of the benefits of slots in the child class especially slot inheritance.

By design, we avoid multiple inheritance and prefer association when shared behaviour is needed.

Rationale: Multiple inheritance is complex and easy to mess up (the infamous deadly diamond of death). You have to be careful with method resolution order (MRO) so that the correct derived methods are called. Then also you have to use super() consistently or never at all.

When shared behaviour cannot be achieved through association, Mixins are the sanctioned exception. A Mixin is a lightweight class that provides a specific set of reusable methods without carrying state. Because they do not use @define or @attrs, they are compatible with slots=True classes and are never meant to be instantiated directly.

Mixins must be defined with empty __slots__ to ensure they do not introduce a __dict__ that would break slot inheritance.

 Correct: Mixin defined with empty slots
class SerialisableMixin:
    __slots__ = ()

    def to_dict(self):
        ...

Lazy Loading and Caching#

For attributes that are not core attributes, we lazy_load them by setting init=False. Furthermore functools.cached_property is used to cache attributes after first access.

The @cached_property is by default not suitable for use with slotted classes because it relies on the presence of a __dict__ to store cached values. However, as of attrs >= 24.1.0, cached_property is supported on slotted classes. See also: how cached properties work on slotted classes.

Warning: cached_property is not thread-safe by default. If the class may be accessed concurrently, we use a threading lock to guard the property computation. Example:

from threading import RLock
from attrs import field
from functools import cached_property

class MyClass:
    _lock: RLock = field(factory=RLock, init=False)

    @cached_property
    def expensive_computation(self):
        with self._lock:
            # perform expensive computation here
            ...

Note: The use of RLock instead of Lock to prevent deadlocks when trying to access a cached property from a another cached property.

Containers#

We are using containers where we do not want to implement any behavior for an object, but useful to have a named and grouped representation of the data. They are defined using @frozen from attrs to create immutable data structures and available in ensembl.vep.common.(containers).