Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/trailmark/models/_fast_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Faster ``__init__`` for plain frozen dataclasses built in large numbers.

A frozen dataclass's generated ``__init__`` assigns each field through
``object.__setattr__``. For a dataclass whose fields are all positional init
fields with plain (immutable) defaults and no ``__post_init__``, filling
``__dict__`` in field order builds the same instance: same attributes, same
``__dict__`` order, and the same signature, defaults and argument validation.
"""

from __future__ import annotations

import dataclasses
import sys
from typing import Any


def fast_init[T: type](cls: T) -> T:
"""Replace ``cls.__init__`` when it is equivalent to fill ``__dict__`` directly."""
fields = dataclasses.fields(cls) # ty: ignore[invalid-argument-type]
if (
hasattr(cls, "__post_init__")
or "__slots__" in cls.__dict__
or any(
not field.init
or field.kw_only
or field.default_factory is not dataclasses.MISSING
or field.name.startswith("__")
for field in fields
)
):
return cls
namespace: dict[str, object] = {}
parameters = []
defaults = []
for field in fields:
parameters.append(field.name)
if field.default is not dataclasses.MISSING:
defaults.append(field.default)
assignments = ", ".join(f"{field.name!r}: {field.name}" for field in fields)
signature = ", ".join(parameters)
source = f"def __init__(self, {signature}):\n self.__dict__.update({{{assignments}}})"
exec( # noqa: S102 - parameters come from the dataclass's own field names
source, vars(sys.modules[cls.__module__]), namespace
)
init: Any = namespace["__init__"]
init.__defaults__ = tuple(defaults) or None
init.__annotations__ = cls.__init__.__annotations__.copy()
init.__qualname__ = f"{cls.__qualname__}.__init__"
init.__module__ = cls.__module__
cls.__init__ = init
return cls
2 changes: 2 additions & 0 deletions src/trailmark/models/edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from dataclasses import dataclass
from enum import Enum

from trailmark.models._fast_init import fast_init
from trailmark.models.nodes import Attribute, SourceLocation


Expand Down Expand Up @@ -33,6 +34,7 @@ class EdgeConfidence(Enum):
UNCERTAIN = "uncertain"


@fast_init
@dataclass(frozen=True)
class CodeEdge:
"""A directed edge in the code graph."""
Expand Down
8 changes: 8 additions & 0 deletions src/trailmark/models/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from enum import Enum
from typing import TYPE_CHECKING

from trailmark.models._fast_init import fast_init

if TYPE_CHECKING:
from trailmark.models.exceptions import ExceptionEvent

Expand Down Expand Up @@ -64,6 +66,7 @@ class NodeOrigin(Enum):
SYNTHETIC = "synthetic"


@fast_init
@dataclass(frozen=True)
class SourceLocation:
"""A span of source code in a file."""
Expand All @@ -75,6 +78,7 @@ class SourceLocation:
end_col: int | None = None


@fast_init
@dataclass(frozen=True)
class TypeRef:
"""A reference to a type, possibly with generic arguments."""
Expand All @@ -84,6 +88,7 @@ class TypeRef:
generic_args: tuple[TypeRef, ...] = ()


@fast_init
@dataclass(frozen=True)
class TypeParameter:
"""A generic type parameter declared by a code unit."""
Expand All @@ -94,6 +99,7 @@ class TypeParameter:
variance: str | None = None


@fast_init
@dataclass(frozen=True)
class Parameter:
"""A function or method parameter."""
Expand All @@ -103,6 +109,7 @@ class Parameter:
default: str | None = None


@fast_init
@dataclass(frozen=True)
class BranchInfo:
"""Metadata about a branch within a function."""
Expand All @@ -112,6 +119,7 @@ class BranchInfo:
complexity_contribution: int = 1


@fast_init
@dataclass(frozen=True)
class CodeUnit:
"""A node in the code graph: function, method, class, or module."""
Expand Down
Loading