Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
Core: Add get_trait_or helper
Browse files Browse the repository at this point in the history
  • Loading branch information
mawildoer committed Aug 27, 2024
1 parent 39d8ded commit f0e7b38
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/faebryk/core/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,16 +436,24 @@ def has_trait(self, trait) -> bool:
return len(self._find(trait, only_implemented=True)) > 0

def get_trait[V: "Trait"](self, trait: Type[V]) -> V:
from faebryk.core.trait import TraitImpl
from faebryk.core.trait import TraitException, TraitImpl, TraitNotFoundError

assert not issubclass(
trait, TraitImpl
), "You need to specify the trait, not an impl"
if not issubclass(trait, TraitImpl):
raise TraitException("You need to specify the trait, not an impl")

candidates = self._find(trait, only_implemented=True)
assert len(candidates) <= 1
assert len(candidates) == 1, "{} not in {}[{}]".format(trait, type(self), self)

if not len(candidates) == 1:
raise TraitNotFoundError(f"{trait} not in {type(self)}[{self}]")

out = candidates[0]
assert isinstance(out, trait)
return out

def get_trait_or[V: "Trait"](self, trait: Type[V], default = None) -> V:
from faebryk.core.trait import TraitNotFoundError
try:
return self.get_trait(trait)
except TraitNotFoundError:
return default
9 changes: 9 additions & 0 deletions src/faebryk/core/trait.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@
import logging

from faebryk.core.node import Node
from faebryk.libs.exceptions import FaebrykException
from faebryk.libs.util import cast_assert

logger = logging.getLogger(__name__)


class TraitException(FaebrykException):
"""Raised for trait related errors."""


class TraitNotFoundError(TraitException):
"""Raised when a trait is not found."""


class Trait(Node):
@classmethod
def impl[T: "Trait"](cls: type[T]):
Expand Down

0 comments on commit f0e7b38

Please sign in to comment.