Skip to content

ExtendedType: speed analysis and improvements #531

Open

Description

@pytooling-claude

This issue collects a speed analysis of ExtendedType (pyTooling.MetaClasses) compared to classic Python classes,
the improvements found, and the pull requests implementing them. Every class of a data model pays ExtendedType's cost
at import time, e.g. pyVHDLModel's 415 classes or pyEDAA.Reports' code coverage and unit testing models.

Summary

Measure Result
Class creation vs. hand-written __slots__ 7.5–9.7× on 3.14, 6.6–9.2× on 3.13. A medium class: 51.6 µs vs. 6.6 µs.
Instance creation +40–60 ns per object on 3.14 only (1.1–1.5×), no difference on 3.13. Caused by CPython, not by ExtendedType.
Attribute, property and method access 1.00×, identical to classic slotted classes. isinstance against an ExtendedType class: +30 ns.
Memory per instance Identical to classic slotted classes.
pyVHDLModel import time spent in ExtendedType 69 %: 37 of 54 ms for 415 classes (3.14). type.__new__ itself is only 6 ms of it.
Measured gain of the exact pure-Python improvements −17 to −19 % of ExtendedType's time on real models; −37 to −60 % per class with from __future__ import annotations.
@readonly read 255 ns vs. 33 ns for @property (3.14); about 66 ns with its overloads under TYPE_CHECKING.
Cython No gain worth it, see below.
Verified on dev (all exact improvements merged) pyVHDLModel −13 to −15 % of ExtendedType's time (3.14; −12 to −14 % on 3.13), pyEDAA.Reports CodeCoverage −15 to −17 %; postponed annotations −54 % per class; @readonly −78 %. See Verified on dev.

ExtendedType's own Python code is about 85 % of its class creation time. Nearly every step is a full scan that runs
for every class, including classes not using the feature: the @expects method scan walks every dictionary of the MRO,
the abstract-method check walks every base's dictionary, and postponed annotations are eval'd one string at a time.

Method

  • pyTooling dev @ 165db01, Python 3.14.7 and 3.13.5, Linux x86-64 (WSL2), Intel i9-11950H, pinned to one core.

  • Variants generated from one specification per hierarchy, so they are equivalent:

    • classic class without __slots__,
    • classic class with hand-written __slots__ (mixins with __slots__ = ()),
    • ExtendedType with slots=True (mixins with mixin=True).

    Every class has annotated fields, an __init__ chain calling super().__init__() and setting all fields, methods and
    properties.

  • Class creation times only the metaclass call; class bodies are executed beforehand. Instances and access via
    timeit, warmed up. Memory via tracemalloc over 20 000 instances.

  • 7 interleaved rounds, 2 full runs per Python version, medians. Run-to-run difference: median 2.5 %, p90 < 8 %.

  • Don't compare the two interpreters with each other: 3.14 is a python.org build, 3.13 is Debian's package. This
    3.14 is slower even for x = [] (19.4 vs. 12.2 ns). All ratios and gains compare within one interpreter.

Survey of real data models

All 507 ExtendedType classes of pyVHDLModel, pyEDAA.Reports (code coverage, unit testing), pyTooling.Graph and
pyTooling.Tree: median 4 fields (inherited included), 0–1 own methods, 1 mixin in the MRO, depth 3. The tail
(p90: 26 fields, 13 methods, 6 mixins, MRO of 11) are document and design-unit classes.

Bin Fields Methods Properties
tiny 2 1 1
small 5 3 3
medium 10 6 6
large 25 15 15
xl 40 30 30

Hierarchy shapes: straight lines of depth 1, 3 and 6; a fishbone (spine of 4, one mixin per level); a diamond (two
mixins sharing a base); one leaf with 4 or 8 mixins; 20 sibling subclasses of one base.

Class creation

µs per class (bins) or per hierarchy (shapes), median.

Case 3.14 classic 3.14 slots 3.14 ExtendedType ratio 3.13 classic 3.13 slots 3.13 ExtendedType ratio
tiny 4.7 4.6 34.5 7.5× 3.3 3.4 22.3 6.6×
small 4.9 5.4 41.1 7.7× 3.4 3.8 28.1 7.4×
medium 5.3 6.6 51.6 7.8× 3.7 4.8 34.6 7.2×
large 6.9 10.4 81.6 7.8× 5.4 7.2 53.0 7.3×
xl 8.6 15.5 122.7 7.9× 6.5 10.8 81.4 7.6×
line, depth 1 9.6 12.3 106.8 8.7× 7.5 8.5 75.0 8.8×
line, depth 3 21.0 22.9 214.7 9.4× 15.1 16.8 155.0 9.2×
line, depth 6 43.9 44.6 420.1 9.4× 31.6 31.6 284.9 9.0×
fishbone 40.0 39.1 357.0 9.1× 28.3 29.5 250.6 8.5×
diamond 27.6 27.3 248.2 9.1× 18.0 20.3 173.6 8.6×
4 mixins 30.5 30.6 258.0 8.4× 23.6 23.4 173.7 7.4×
8 mixins 52.5 51.3 415.2 8.1× 37.1 37.6 280.9 7.5×
20 siblings 111.2 118.2 1144.9 9.7× 77.3 85.0 786.1 9.2×

What it scales with, in ExtendedType's own µs per unit (3.14 / 3.13): +4.5 / +1.9 per depth level, +9.1 / +4.9 per
mixin, +6.1 / +4.4 per postponed (string) annotation, +2.2 / +1.1 per abstract method, +1.7 / +1.0 per method,
+1.2 / +0.4 per ClassVar, +0.7 / +0.4 per property, +0.6 / +0.4 per field. An almost empty class costs about 27 µs
(3.14) or 17 µs (3.13) more than with classic slots.

Instance creation

ns per instance of the leaf, C(1) with a full __init__ chain, median.

Case 3.14 classic 3.14 slots 3.14 ExtendedType ratio 3.13 classic 3.13 slots 3.13 ExtendedType ratio
tiny 88 78 118 1.51× 51 72 70 0.97×
small 98 85 129 1.52× 68 85 87 1.03×
medium 120 103 146 1.42× 96 123 118 0.96×
large 181 159 202 1.28× 179 222 207 0.93×
xl 1355 213 252 1.18× 635 299 291 0.97×
line, depth 6 403 391 448 1.14× 329 360 336 0.93×
fishbone 323 310 373 1.20× 339 356 354 1.00×
8 mixins 346 328 380 1.16× 407 418 418 1.00×

Cause of the +40–60 ns on 3.14: CPython 3.14 specialises C(...) to CALL_ALLOC_AND_ENTER_INIT only if
type(C) is type, because a metaclass could override __call__. With any metaclass, even class Meta(type): pass,
the call stays CALL_NON_PY_GENERAL; a do-nothing metaclass measures the same as ExtendedType. 3.13 doesn't
specialise slotted classes at all, so there is no gap. ExtendedType doesn't override __call__, so this can only be
changed in CPython (e.g. test "the metaclass doesn't override __call__" instead of the exact type).

The xl classic row: a dict-based class with more than 30 attributes leaves CPython's inline-values layout (1160 B
per instance), independent of ExtendedType.

Access and memory

  • Reads, writes, properties and method calls of ExtendedType instances equal classic slotted classes.
  • isinstance against a class whose metaclass is not type leaves CPython's fast path (unless it's an exact-type
    hit): +30 ns (3.14) / +23 ns (3.13). A do-nothing metaclass shows the same.
  • Instances are byte for byte classic slotted instances. Exception: a diamond lists the shared mixin's slot twice
    (+8 B per instance), fixed by Reject a mixin-class' slot that exists already, and add a diamond's slot once #504.
  • @readonly subclasses property and, since v9.0.0, overrides __get__ in Python only so type checkers see the
    getter's return type. Every read runs two Python frames plus super(): 255 ns vs. 33 ns for a @property
    (3.14). Moving the __get__ overloads under if TYPE_CHECKING: keeps the typing and gives about 66 ns.
    pyVHDLModel has 270 @readonly properties, pyEDAA.Reports 214.

Factors

  • Abstract members: +2.2 µs per abstract method at class creation (3.14). Instances of a concrete subclass of an
    abstract class cost +145 ns (3.14) / +107 ns (3.13), because _wrapNewMethodIfAbstract installs a Python
    wrapped_new to undo the inherited abstract_new (workaround for Cannot set A.__new__ back to object.__new__ once it is set to something else. python/cpython#105888). ABCMeta needs no
    per-instance work, it uses CPython's own abstract flag.
  • Slot initial values: dev drops them (fixed by MetaClasses: assign a slotted field's initial value in an intermediate __init__ #524). With MetaClasses: assign a slotted field's initial value in an intermediate __init__ #524, each instance pays 1.4 µs for 2 defaults and
    2.9 µs for 5 (133 → 884 ns for one default, 6.7×), because hasattr(self, field) on a not yet assigned slot raises
    and swallows an AttributeError (322 ns each), plus the *args, **kwargs wrapper. Assigning the defaults in a
    __new__ wrapper instead keeps the semantics and halves it (452 ns).
  • ClassVars: +1.2 µs each (3.14), annotation resolution and classification.
  • Postponed annotations (from __future__ import annotations, in 13 of 24 pyVHDLModel and 16 of 19 pyEDAA.Reports
    files): every string is compiled and eval'd in _resolveAnnotation, +6.1 µs per field (3.14). A medium class
    doubles from 51 to 108 µs. Compiling costs 7 µs per string, evaluating cached code 0.4 µs.
  • Mixin contracts: the expects= class keyword is cheap when used (+2.6 µs for a mixin expecting 2 names). The
    method-level @expects support is not: _wrapMethodsWithUnfulfilledExpectations scans every member of every class
    in the MRO for every new class, whether anything uses @expects or not: 7 µs for a flat class, 24–27 µs for a depth-6
    or 8-mixin leaf, 16 % of pyVHDLModel's ExtendedType time.

Where the time goes

Steps of ExtendedType.__new__ while importing pyVHDLModel (3.14, wrapped with timers, 46 ms in total):

Step ms
_computeSlots (incl. annotation eval 5.9 ms, mixin slot aggregation 2.6 ms) 14.4
_wrapMethodsWithUnfulfilledExpectations 7.6
type.__new__ (CPython) 5.8
_checkForAbstractMethods 4.7
_findMethods 4.2

Depth and mixins scale worst, because the expects scan (all MRO dictionaries), the abstract check (all direct bases'
dictionaries, about 20 injected bookkeeping members each), the inherited-slot map (whole primary MRO) and the mixin
slot aggregation (every inheritance path) recompute from scratch what the bases already knew.

Real models (fresh process per sample):

Model Python Import in ExtendedType.__new__ classes
pyVHDLModel 3.14 54 ms 37.4 ms (69 %) 415
pyVHDLModel 3.13 42.7 ms 28.6 ms 415
pyEDAA.Reports 3.14 104 ms (incl. lxml) 16.9 ms 135

Improvements (prototyped and measured)

Each change keeps every feature, error message, exception type and note, except 03b. Gain = time inside
ExtendedType.__new__ while importing pyVHDLModel (412 classes, minimum of 15 fresh processes).

# Change 3.14 3.13 Exact
01 Annotation code cache: each annotation text is compiled once (same result as eval(str)) −2.6 % −8.0 % yes; −26 to −57 % per class with the future import
02 Abstract-method check: test the name first; skip the base scan when no base has abstract methods −5.7 % −8.2 % yes
03a @expects scan skips object −2.2 % −2.7 % yes
03b @expects scan cache: each class keeps its marked members (__markedMembers__) −14.3 % −14.6 % no, decision needed
05 Non-abstract path of _wrapNewMethodIfAbstract without raise/catch; tuple fast path for expects −3.2 % −2.3 % yes
07 Skip the recursive __slots__ walk when every direct base is a slotted ExtendedType class −1.6 % −3.0 % yes
04, 06, 08 ThisClass rebinding, unannotated-field check, _findMethods hoisting +3.4 … −0.3 % noise or slower: not proposed
10 01 + 02 + 03a + 05 + 06 + 07 + 08 −18.5 % −16.7 % yes
11 10 with 03b instead of 03a −24.8 % −23.3 % 03b
pyVHDLModel, 412 classes dev exact set (10) with 03b (11)
3.14, in ExtendedType.__new__ 32.1 ms 26.1 ms 23.5 ms
3.13, in ExtendedType.__new__ 25.9 ms 21.6 ms 19.9 ms
3.14, whole import 46 ms 40 ms 38 ms
3.14, per class 78 µs 63 µs 57 µs

Class creation per class family (µs per class including the class body):

Family 3.14 dev 3.14 exact set 3.13 dev 3.13 exact set
small 36.0 28.5 (−21 %) 22.7 19.9 (−12 %)
small, future import 52.9 28.8 (−46 %) 36.5 21.2 (−42 %)
code coverage like 71.5 63.5 (−11 %) 56.0 48.8 (−13 %)
code coverage like, future import 95.3 58.5 (−39 %) 72.0 45.4 (−37 %)
large 106.5 94.5 (−11 %) 72.8 68.8 (−5 %)
large, future import 249.5 99.8 (−60 %) 164.3 68.9 (−58 %)
deep 51.4 42.2 (−18 %) 39.2 34.0 (−14 %)
deep, future import 71.9 40.7 (−43 %) 51.5 31.0 (−40 %)

Instance creation is unchanged by every change (±3 %). All changes pass pyTooling's unit tests (3.14; MetaClasses
tests also on 3.13), pyVHDLModel's and pyEDAA.Reports' tests.

Not considered: __init_subclass__ instead of a metaclass; it runs after type.__new__, too late to set __slots__.

Cython

Question: simple Cython didn't help pyTooling; could more Cython features help ExtendedType?

  • What could be compiled: type.__new__ (already C) is 14–16 % of ExtendedType's time on dev and about 24 %
    after the improvements; the class body runs in the user's uncompiled module. The rest is Python-level work made of
    C-API calls on generic objects (dictionary iteration, getattr/hasattr/isinstance, closures, eval), which
    compiled code calls the same way. Only bytecode dispatch is saved.
  • MetaClasses compiled alone (Cython 3.3.0): pyVHDLModel 32.7 → 25.2 ms on dev, 24.1 → 19.4 ms on top of
    the improvements (11). But:
    • without annotation typing no class can be created (baseClasses: tuple[type] is an exact type check);
    • with typing (type → type[Any]), 138 of 2455 tests fail: compiled functions aren't FunctionType, so abstract
      methods are detected wrongly; a __prepare__ returning a dict subclass breaks; messages become Cython's;
    • 24 wheels (3.11–3.14 × 6 systems), 2.7 MB per module (440 KB stripped).
  • Hot loops compiled with C types: at most 3.6 ms per pyVHDLModel import on dev, about 1.5 ms after 03b.
  • Metaclass as cdef class CMeta(type): compiles, but can't define __new__, only __cinit__, which runs after
    the class exists: too late to compute __slots__.

Verdict: no Cython. The pure-Python improvements (24.1 ms) already beat compiled dev (25.2 ms) without any
behaviour change. The per-instance and isinstance costs come from CPython's handling of a metaclass, which Cython
can't change either.

Bugs found on the way

  1. A mixin's expectation fulfilled one level below rejects constructor arguments.
    _wrapNewMethodIfExpectationUnfulfilled restores object.__new__ into the fulfilling class' dictionary, which hits
    Cannot set A.__new__ back to object.__new__ once it is set to something else. python/cpython#105888 (_wrapNewMethodIfAbstract works around it, this path doesn't).
    class Root(metaclass=ExtendedType, slots=True):
      _a: int
      def __init__(self, a): self._a = a
    class Mx(metaclass=ExtendedType, mixin=True, expects=("Run",)): pass
    class Mid(Root, Mx): pass        # misses 'Run'
    class Leaf(Mid):
      def Run(self): pass
    Leaf(1)  # TypeError: object.__new__() takes exactly one argument (the type to instantiate)
  2. An unmarked override of an @expects method gets the base's stub back. The @expects scan never drops a marked
    name when a derived class redefines the method without the marker.
    class Base(metaclass=ExtendedType, slots=True):
      @expects("Missing")
      def Method(self): return "base"
    class Derived(Base):
      def Method(self): return "derived"   # needs nothing
    Derived().Method()  # UnfulfilledExpectationError: Method 'Derived.Method()' expects members ...

Verified on dev

Base 165db01 (the measurements above) vs. dev b1c6638, measured in one session with interleaved rounds, Python 3.14.7
and 3.13.5. Merged: 01 (#534), 02 (#535), 03a (#536), 05 (#537), 07 (#538), @readonly (#539); not merged: 03b, 06, 08.
Bug fixes merged afterwards that touch class creation: #532, #533, #524 with #544, #504. Today's absolute times are
8–13 % slower than in the original session, so only compare within this section.

Model, time in ExtendedType.__new__ base prototype 10, re-measured dev predicted
pyVHDLModel, 412 classes, 3.14 34.5 ms 27.7 ms (−19.7 %) 29.9 ms (−13.3 %), 83.8 → 72.6 µs per class −18.5 %
pyVHDLModel, 412 classes, 3.13 27.2 ms 23.8 ms (−12.5 %) 24.2 ms (−10.9 %) −16.7 %
pyEDAA.Reports CodeCoverage, 17 classes, 3.14 1.92 ms 1.61 ms (−16.1 %) 1.59 ms (−17.2 %) −17.0 %

Round 2 (2026-10-12, idle machine, fixed hash seed, warm .pyc; noise 1.9–3.6 %, round 1: 5–10 %):

pyVHDLModel, ExtendedType.__new__ 3.14 3.13
base → dev, GC enabled (what users see) −14.8 % (37.6 → 32.2 ms) −11.7 %
base → dev, GC disabled (the code's own cost) −13.2 % (34.4 → 30.1 ms) −13.7 % (26.5 → 22.4 ms)
prototype 10, re-measured −19.2 % −14.3 %
speed PRs #534–#538 alone −18.4 % −16.8 % (GC disabled)
  • The "checkout effect" of round 1 was garbage collection: on 3.13 about 3 ms of a 27 ms import are GC pauses, and where a
    full collection lands depends on exact allocation counts, which are fixed per code version - so it looked like a few
    percent between versions. Path, hash seed and order were ruled out. On 3.13, bytecode compiled during the import makes
    ExtendedType.__new__ 11.7 % faster than the same code from .pyc (3.14: no difference). Round 1's per-merge numbers
    (Reject a mixin-class' slot that exists already, and add a diamond's slot once #504 +5 % / +9 %) are therefore replaced by the GC-disabled ones above.
  • Synthetic matrix: hierarchies −11 to −17 %, flat classes −2 to −7 % on both Pythons; class creation vs. hand-written
    __slots__ 7.2–9.7× → 6.7–8.0× (3.14); @readonly 185.3 → 41.3 ns; instance creation unchanged.

The artifact's section Verified on dev has the full tables: synthetic bins and shapes, step profile, per-instance
costs and caveats.

Decisions

Pull Requests

Activity

  1. added
    Enhancement
    MetaClass
    ExtendedType
    on Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementExtendedTypeMetaClass

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions