capellambse.model package

Implements a high-level interface to Capella projects.

class capellambse.model.Accessor

Bases: Generic[T_co]

Super class for all Accessor types.

__init__()
Return type:

None

class capellambse.model.Alias

Bases: Accessor[T_co]

Provides an alias to another attribute.

Parameters:
  • target (str) – The target to redirect to.

  • dirhide (bool) – If True, hide this alias from dir() calls.

__init__(target, /, *, dirhide=True)
Parameters:
Return type:

None

dirhide
target
class capellambse.model.Allocation

Bases: WritableAccessor[T_co], PhysicalAccessor[T_co]

Accesses elements through reference elements.

__init__(tag, xtype, /, *, aslist=None, mapkey=None, mapvalue=None, attr, backattr=None, unique=True)

Define an Allocation.

Allocations use link elements (often named like “SomethingAllocation”), which only contain a link to the target and sometimes also the source element.

If the link element has anything other than these, e.g. its own name or a type, use Containment instead and create a shortcut to the target with a small @property.

Parameters:
  • tag (str | None) – The XML tag that the reference elements will have.

  • xtype (str | type[ModelElement]) – The xsi:type that the reference elements will have. This has no influence on the elements that are referenced.

  • attr (str) – The attribute on the reference element that contains the actual link.

  • backattr (str | None) – An optional attribute on the reference element to store a reference back to the owner (parent) object.

  • aslist (type[ElementList] | None) – Optionally specify a different subclass of ElementList.

  • mapkey (str | None) –

    Specify the attribute to look up when the returned list is indexed with a str. If not specified, str indexing is not possible.

    Ignored if aslist is not specified.

  • mapvalue (str | None) –

    If specified, return this attribute of the found object when using str indices into the returned list. If not specified, the found object itself is returned.

    Ignored if aslist is not specified.

  • unique (bool) – Enforce that each element may only appear once in the list. If a duplicate is attempted to be added, an exception will be raised. Note that this does not have an effect on lists already existing within the loaded model.

Return type:

None

backattr: str | None
delete(elmlist, obj)

Delete the obj from the model.

Return type:

None

Parameters:
insert(elmlist, index, value)

Insert the value object into the model.

The object must be inserted at an appropriate place, so that, if elmlist were to be created afresh, value would show up at index index.

Return type:

None

Parameters:
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
tag: str | None
unique
class capellambse.model.AlternateAccessor

Bases: Accessor[T_co]

Provides access to an “alternate” form of the object.

__init__(class_)
Parameters:

class_ (type[T_co])

class_
class capellambse.model.Association

Bases: WritableAccessor[T_co], PhysicalAccessor[T_co]

Provides access to elements that are linked in an attribute.

__init__(class_, attr, *, aslist=None, mapkey=None, mapvalue=None, fixed_length=0)

Define an Association.

Associations are stored as simple links in an XML attribute.

Parameters:
  • class – The proxy class. Currently only used for type hints.

  • attr (str) – The XML attribute to handle.

  • aslist (type[ElementList] | None) – If None, the attribute contains at most one element reference, and either None or the constructed proxy will be returned. If not None, must be a subclass of ElementList. It will be used to return a list of all matched objects.

  • mapkey (str | None) –

    Specify the attribute to look up when the returned list is indexed with a str. If not specified, str indexing is not possible.

    Ignored if aslist is not specified.

  • mapvalue (str | None) –

    If specified, return this attribute of the found object when using str indices into the returned list. If not specified, the found object itself is returned.

    Ignored if aslist is not specified.

  • fixed_length (int) –

    When non-zero, the returned list will try to stay at exactly this length, by not allowing to insert or delete beyond this many members.

    Ignored if aslist is not specified.

  • class_ (type[T_co] | None)

attr
delete(elmlist, obj)

Delete the obj from the model.

Return type:

None

Parameters:
insert(elmlist, index, value)

Insert the value object into the model.

The object must be inserted at an appropriate place, so that, if elmlist were to be created afresh, value would show up at index index.

Return type:

None

Parameters:
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
class capellambse.model.AttributeMatcherAccessor

Bases: DirectProxyAccessor[T_co]

__init__(class_, xtypes=None, *, aslist=None, attributes, **kwargs)

Create a DirectProxyAccessor.

Parameters:
  • class – The proxy class.

  • xtypes (str | type[TypeVar(T_co, bound= ModelObject, covariant=True)] | Iterable[str | type[TypeVar(T_co, bound= ModelObject, covariant=True)]] | None) – The xsi:type(s) of the child element(s). If None, then the constructed proxy will be passed the original element instead of a child.

  • aslist (type[ElementList] | None) – If None, only a single element must match, which will be returned directly. If not None, must be a subclass of ElementList, which will be used to return a list of all matched objects.

  • mapkey

    Specify the attribute to look up when the returned list is indexed with a str. If not specified, str indexing is not possible.

    Ignored if aslist is not specified.

  • mapvalue

    If specified, return this attribute of the found object when using str indices into the returned list. If not specified, the found object itself is returned.

    Ignored if aslist is not specified.

  • fixed_length

    When non-zero, the returned list will try to stay at exactly this length, by not allowing to insert or delete beyond this many members.

    Ignored if aslist is not specified.

  • follow_abstract – Follow the link in the abstractType XML attribute of each list member and instantiate that object instead. The default is to instantiate the child elements directly.

  • rootelem – A class or xsi:type (or list thereof) that defines the path from the current object’s XML element to the search root. If None, the current element will be used directly.

  • single_attr – If objects can be created with only a single attribute specified, this argument is the name of that attribute. This create_singleattr().

  • class_ (type[T_co])

  • attributes (dict[str, Any])

Return type:

None

attributes
class capellambse.model.Backref

Bases: PhysicalAccessor[T_co]

Searches for references to the current element elsewhere.

__init__(class_, *attrs, aslist=None, mapkey=None, mapvalue=None)

Define a back-reference.

This relation is not actually stored in the model, but nevertheless provides a useful shortcut to other related elements.

Parameters:
  • class – The type of class to search for references on.

  • attrs (str) – The attributes of the target classes to search through.

  • aslist (type[ElementList] | None) – If None, only a single element must match, which will be returned directly. If not None, must be a subclass of ElementList, which will be used to return a list of all matched objects.

  • mapkey (str | None) –

    Specify the attribute to look up when the returned list is indexed with a str. If not specified, str indexing is not possible.

    Ignored if aslist is not specified.

  • mapvalue (str | None) –

    If specified, return this attribute of the found object when using str indices into the returned list. If not specified, the found object itself is returned.

    Ignored if aslist is not specified.

  • class_ (type[T_co] | tuple[type[ModelObject], ...])

Return type:

None

attrs: tuple[attrgetter, ...]
target_classes: tuple[type[ModelObject], ...]
class capellambse.model.BasePOD

Bases: Generic[U]

A plain-old-data descriptor.

NOT_OPTIONAL = <object object>
__init__(attribute, *, default, writable)
Parameters:
  • attribute (str)

  • default (U)

  • writable (bool)

Return type:

None

attribute
default
writable
class capellambse.model.BoolPOD

Bases: BasePOD[bool]

A POD containing a boolean.

__init__(attribute, /)

Create a BoolPOD.

Parameters:

attribute (str) – The name of the attribute on the XML element.

Return type:

None

class capellambse.model.CachedElementList

Bases: ElementList[T], Generic[T]

An ElementList that caches the constructed proxies by UUID.

__init__(model, elements, elemclass, *, cacheattr=None, **kw)

Create a CachedElementList.

Parameters:
  • model (MelodyModel) – The model that all elements are a part of.

  • elements (list[_Element]) – The members of this list.

  • elemclass (type[TypeVar(T, bound= ModelObject)]) – The ModelElement subclass to use for reconstructing elements.

  • cacheattr (str | None) – The attribute on the model to use as cache.

  • **kw (Any) – Additional arguments are passed to the superclass.

Return type:

None

class capellambse.model.Containment

Bases: WritableAccessor, PhysicalAccessor

__init__(role_tag, classes=(), *, aslist=None, mapkey=None, mapvalue=None, alternate=None)
Parameters:
Return type:

None

alternate: type[ModelElement] | None
classes
create(elmlist, typehint=None, /, **kw)

Create and return a new element of type elmclass.

Parameters:
  • elmlist (ElementListCouplingMixin) – The (coupled) ElementList to insert the new object into.

  • typehint (str | None) – Hints for finding the correct type of element to create. Can either be a full or shortened xsi:type string, or an abbreviation defined by the specific Accessor instance.

  • kw (Any) – Initialize the properties of the new object. Depending on the object’s type, some attributes may be required.

Return type:

ModelElement

delete(elmlist, obj)

Delete the obj from the model.

Return type:

None

Parameters:
insert(elmlist, index, value)

Insert the value object into the model.

The object must be inserted at an appropriate place, so that, if elmlist were to be created afresh, value would show up at index index.

Return type:

None

Parameters:
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
role_tag
class capellambse.model.DatetimePOD

Bases: BasePOD[datetime | None]

A POD containing a timestamp.

The value stored in the XML will be formatted as required by Capella. This format is the ISO8601 format with millisecond precision, but no : in the time zone specification.

__init__(attribute, /, *, writable=True)

Create a DatetimePOD.

Parameters:
  • attribute (str) – The name of the attribute on the XML element.

  • writable (bool) – Whether to allow changing the value at runtime.

Return type:

None

re_get = re.compile('(?<=[+-]\\d\\d)(?=\\d\\d$)')
re_set = re.compile('(?<=[+-]\\d\\d):(?=\\d\\d$)')
class capellambse.model.DeepProxyAccessor

Bases: PhysicalAccessor[T_co]

A DirectProxyAccessor that searches recursively through the tree.

__init__(class_, xtypes=None, *, aslist=None, rootelem=None)

Create a DeepProxyAccessor.

Parameters:
  • class – The proxy class.

  • xtypes (str | type[TypeVar(T_co, bound= ModelObject, covariant=True)] | Iterable[str | type[TypeVar(T_co, bound= ModelObject, covariant=True)]] | None) – The xsi:type (or types) to search for. If None, defaults to the type of the passed class_.

  • aslist (type[ElementList] | None) – A subclass of ElementList to use for returning a list of all matched objects. If not specified, defaults to the base ElementList.

  • rootelem (type[ModelElement] | Sequence[type[ModelElement]] | None) – Limit the search scope to objects of this type, nested below the current object. When passing a sequence, defines a path of object types to follow.

  • class_ (type[T_co])

Return type:

None

class capellambse.model.DeprecatedAccessor

Bases: Accessor[T_co]

Provides a deprecated alias to another attribute.

__init__(alternative, /)
Parameters:

alternative (str)

Return type:

None

alternative
class capellambse.model.DirectProxyAccessor

Bases: WritableAccessor[T_co], PhysicalAccessor[T_co]

Creates proxy objects on the fly.

__init__(class_, xtypes=None, *, aslist=None, mapkey=None, mapvalue=None, fixed_length=0, follow_abstract=False, rootelem=None, single_attr=None)

Create a DirectProxyAccessor.

Parameters:
  • class – The proxy class.

  • xtypes (str | type[TypeVar(T_co, bound= ModelObject, covariant=True)] | Iterable[str | type[TypeVar(T_co, bound= ModelObject, covariant=True)]] | None) – The xsi:type(s) of the child element(s). If None, then the constructed proxy will be passed the original element instead of a child.

  • aslist (type[ElementList] | None) – If None, only a single element must match, which will be returned directly. If not None, must be a subclass of ElementList, which will be used to return a list of all matched objects.

  • mapkey (str | None) –

    Specify the attribute to look up when the returned list is indexed with a str. If not specified, str indexing is not possible.

    Ignored if aslist is not specified.

  • mapvalue (str | None) –

    If specified, return this attribute of the found object when using str indices into the returned list. If not specified, the found object itself is returned.

    Ignored if aslist is not specified.

  • fixed_length (int) –

    When non-zero, the returned list will try to stay at exactly this length, by not allowing to insert or delete beyond this many members.

    Ignored if aslist is not specified.

  • follow_abstract (bool) – Follow the link in the abstractType XML attribute of each list member and instantiate that object instead. The default is to instantiate the child elements directly.

  • rootelem (str | type[ModelElement] | Sequence[str | type[ModelElement]] | None) – A class or xsi:type (or list thereof) that defines the path from the current object’s XML element to the search root. If None, the current element will be used directly.

  • single_attr (str | None) – If objects can be created with only a single attribute specified, this argument is the name of that attribute. This create_singleattr().

  • class_ (type[T_co])

create(elmlist, typehint=None, /, **kw)

Create and return a new element of type elmclass.

Parameters:
  • elmlist (ElementListCouplingMixin) – The (coupled) ElementList to insert the new object into.

  • typehint (str | None) – Hints for finding the correct type of element to create. Can either be a full or shortened xsi:type string, or an abbreviation defined by the specific Accessor instance.

  • kw (Any) – Initialize the properties of the new object. Depending on the object’s type, some attributes may be required.

Return type:

TypeVar(T_co, bound= ModelObject, covariant=True)

delete(elmlist, obj)

Delete the obj from the model.

Return type:

None

Parameters:
follow_abstract: bool
insert(elmlist, index, value)

Insert the value object into the model.

The object must be inserted at an appropriate place, so that, if elmlist were to be created afresh, value would show up at index index.

Return type:

None

Parameters:
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
rootelem: Sequence[str]
single_attr: str | None
class capellambse.model.E

TypeVar for “Enum”.

alias of TypeVar(‘E’, bound=Enum)

class capellambse.model.ElementList

Bases: MutableSequence[T], Generic[T]

Provides access to elements without affecting the underlying model.

__init__(model, elements, elemclass=None, *, mapkey=None, mapvalue=None)
Parameters:
Return type:

None

create(typehint=None, /, **kw)
Return type:

TypeVar(T, bound= ModelObject)

Parameters:
  • typehint (str | None)

  • kw (Any)

create_singleattr(arg)
Return type:

TypeVar(T, bound= ModelObject)

Parameters:

arg (Any)

delete_all(**kw)

Delete all matching objects from the model.

Return type:

None

Parameters:

kw (Any)

filter(predicate)

Filter this list with a custom predicate.

The predicate may be the name of an attribute or a callable, which will be called on each list item. If the attribute value or the callable’s return value is truthy, the item is included in the resulting list.

When specifying the name of an attribute, nested attributes can be chained using ., like "parent.name" (which would pick all elements whose parent has a non-empty name).

Return type:

ElementList[TypeVar(T, bound= ModelObject)]

Parameters:

predicate (str | Callable[[T], bool])

get(key, default=None)
Return type:

Any

Parameters:
insert(index, value)

S.insert(index, value) – insert value before index

Return type:

None

Parameters:
  • index (int)

  • value (T)

is_coupled()
Return type:

bool

items()
Return type:

ElementListMapItemsView[TypeVar(T, bound= ModelObject)]

keys()
Return type:

ElementListMapKeyView

map(attr)

Apply a function to each element in this list.

If the argument is a string, it is interpreted as an attribute name, and the value of that attribute is returned for each element. Nested attribute names can be chained with ..

If the argument is a callable, it is called for each element, and the return value is included in the result. If the callable returns a sequence, the sequence is flattened into the result.

Duplicate values and Nones are always filtered out.

It is an error if a callable returns something that is not a model element or a flat sequence of model elements.

Parameters:

attr (str | _MapFunction[T])

Return type:

ElementList

values()
Return type:

ElementList[TypeVar(T, bound= ModelObject)]

class capellambse.model.ElementListCouplingMixin

Bases: ElementList[T], Generic[T]

Couples an ElementList with an Accessor to enable write support.

This class is meant to be subclassed further, where the subclass has both this class and the originally intended one as base classes (but no other ones, i.e. there must be exactly two bases). The Accessor then inserts itself as the _accessor class variable on the new subclass. This allows the mixed-in methods to delegate actual model modifications to the Accessor.

__init__(*args, parent, fixed_length=0, **kw)
Parameters:
Return type:

None

create(typehint=None, /, **kw)

Make a new model object (instance of ModelElement).

Instead of specifying the full xsi:type including the namespace, you can also pass in just the part after the : separator. If this is unambiguous, the appropriate layer-specific type will be selected automatically.

This method can be called with or without the layertype argument. If a layertype is not given, all layers will be tried to find an appropriate xsi:type handler. Note that setting the layertype to None explicitly is different from not specifying it at all; None tries only the “Transverse modelling” type elements.

Parameters:
  • typehint (str | None) – Hints for finding the correct type of element to create. Can either be a full or shortened xsi:type string, or an abbreviation defined by the specific Accessor instance.

  • kw (Any) – Initialize the properties of the new object. Depending on the object, some attributes may be required.

Return type:

TypeVar(T, bound= ModelObject)

create_singleattr(arg)

Make a new model object (instance of ModelElement).

This new object has only one interesting attribute. :rtype: TypeVar(T, bound= ModelObject)

See also

ElementListCouplingMixin.create()

More details on how elements are created.

WritableAccessor.create_singleattr()

The method to override in Accessors in order to implement this operation.

Parameters:

arg (Any)

Return type:

T

insert(index, value)

S.insert(index, value) – insert value before index

Return type:

None

Parameters:
  • index (int)

  • value (T)

is_coupled()
Return type:

bool

class capellambse.model.ElementListMapItemsView

Bases: Sequence[tuple[Any, T]], Generic[T]

__init__(parent, /)
Return type:

None

class capellambse.model.ElementListMapKeyView

Bases: Sequence

__init__(parent, /)
Return type:

None

class capellambse.model.EnumPOD

Bases: BasePOD[E]

A POD that can have one of a pretermined set of values.

This works in much the same way as the StringPOD, except that the returned and consumed values are not simple strings, but members of the Enum that was passed into the constructor.

When assigning, this property also accepts the string name of one of the enum members. In either case, the corresponding enum member’s value will be placed in the underlying XML element.

The default constructor argument determines which member will be used if the attribute is missing from the XML. If no default is passed exlicitly, the first declared enum member will be used.

__init__(attribute, enumcls, /, default=None, *, writable=True)

Create an EnumPOD.

Parameters:
  • attribute (str) – The name of the attribute on the XML element.

  • enumcls (type[TypeVar(E, bound= Enum)]) – The enum.Enum subclass to use. The class’ members’ values are used as the possible values for the XML attribute.

  • default (Union[TypeVar(E, bound= Enum), str, None]) – The default value to return if the attribute is not present in the XML. If not passed or None, the first member of the given enumcls will be used.

  • writable (bool) – Whether to allow changing the value at runtime.

Return type:

None

enumcls
class capellambse.model.FloatPOD

Bases: BasePOD[float]

A POD containing a floating-point number.

In Capella’s Java land, these are often called “real numbers”.

__init__(attribute, /, *, writable=True)

Create an IntPOD.

Parameters:
  • attribute (str) – The name of the attribute on the XML element.

  • writable (bool) – Whether to allow changing the value at runtime.

Return type:

None

class capellambse.model.HTMLStringPOD

Bases: BasePOD[Markup]

A POD containing a string with HTML inside.

__init__(attribute, /, *, writable=True)

Create an HTMLStringPOD.

Parameters:
  • attribute (str) – The name of the attribute on the XML element.

  • writable (bool) – Whether to allow changing the value at runtime.

Return type:

None

class capellambse.model.IndexAccessor

Bases: Accessor[T_co]

Access a specific index in an ElementList of a fixed size.

__init__(wrapped, index)
Parameters:
Return type:

None

index
wrapped
class capellambse.model.IntPOD

Bases: BasePOD[int]

A POD containing an integer number.

__init__(attribute, /, *, writable=True)

Create an IntPOD.

Parameters:
  • attribute (str) – The name of the attribute on the XML element.

  • writable (bool) – Whether to allow changing the value at runtime.

Return type:

None

exception capellambse.model.InvalidModificationError

Bases: RuntimeError

Raised when a modification would result in an invalid model.

class capellambse.model.MelodyModel

Bases: object

Provides high-level access to a model.

This class builds upon the lower-level MelodyLoader to provide an abstract, high-level interface for easy access to various model aspects.

__init__(path, *, diagram_cache=None, fallback_render_aird=False, **kwargs)

Load a project.

For complete information on which exact kwargs are supported, consult the documentation of the used file handler. Refer to the “See Also” section for a collection of links.

Below are some common parameter names and their usual meanings. Not all file handlers support all parameters.

Note

Passing in arguments that are not accepted by the selected file handler will result in an exception being raised. Similarly, leaving out arguments that are required by the file handler will also result in an exception.

Parameters:
  • path (str | PathLike) –

    Path or URL to the project. The following formats are accepted:

    • A path to a local .aird file.

    • A path to a local directory (requires entrypoint).

    • An SCP-style short URL, which will be treated as referring to a Git repository.

      Example: git@github.com:DSD-DBS/py-capellambse.git

    • A remote URL, with a protocol or prefix that indicates which file handler to invoke (requires entrypoint).

      Some examples:

      • git://git.example.com/model/coffeemaker.git

      • git+https://git.example.com/model/coffeemaker.git

      • git+ssh://git@git.example.com/model/coffeemaker.git

      Note

      Depending on the exact file handler, saving back to a remote location might fail with update_cache set to False. See save() for more details.

  • entrypoint (str) – Entrypoint from path to the main .aird file.

  • revision (str) – The revision to use, if loading a model from a version control system like git. Defaults to the current HEAD. If the used VCS does not have a notion of “current HEAD”, this argument is mandatory.

  • disable_cache (bool) – Disable local caching of remote content.

  • update_cache (bool) – Update the local cache. Defaults to True, but can be disabled to reuse the last cached state.

  • identity_file (str | pathlib.Path) – The identity file (private key) to use when connecting via SSH.

  • known_hosts_file (str | pathlib.Path) – The known_hosts file to pass to SSH for verifying the server’s host key.

  • username (str) – The username to log in as remotely.

  • password (str) – The password to use for logging in. Will be ignored when identity_file is passed as well.

  • diagram_cache (str | PathLike | FileHandler | dict[str, Any] | None) –

    An optional place where to find pre-rendered, cached diagrams. When a diagram is found in this cache, it will be loaded from there instead of being rendered on access. Note that diagrams will only be loaded from there, but not be put back, i.e. to use it effectively, the cache has to be pre-populated.

    This argument accepts the following values:

    • None, in which case all diagrams will be rendered internally the first time they are used.

    • A path to a local directory.

    • A URL just like for the path argument.

    • A dictionary with the arguments to a FileHandler. The dict’s path key will be analyzed to determine the correct FileHandler class.

    • An instance of FileHandler, which will be used directly.

    Warning

    When using the diagram cache, always make sure that the cached diagrams actually match the model version that is being used. There is no way to check this automatically.

    The file names looked up in the cache built in the format uuid.ext, where uuid is the UUID of the diagram (as reported by diag_obj.uuid) and ext is the render format. Example:

    • Diagram ID: _7FWu4KrxEeqOgqWuHJrXFA

    • Render call: diag_obj.as_svg or diag_obj.render("svg")

    • Cache file name: _7FWu4KrxEeqOgqWuHJrXFA.svg

    This argument is **not* passed to the file handler.*

  • fallback_render_aird (bool) – If set to True, enable the internal engine to render diagrams that were not found in the pre-rendered cache. Defaults to False, which means an exception is raised instead. Ignored if no diagram_cache was specified.

  • **kwargs (Any) – Additional arguments are passed on to the underlying MelodyLoader, which in turn passes it on to the primary resource’s FileHandler.

Return type:

None

See also

capellambse.filehandler.FileHandler

Abstract super class for file handlers. Contains information needed for implementing custom handlers.

capellambse.filehandler.local.LocalFileHandler

The file handler responsible for local files and directories.

capellambse.filehandler.git.GitFileHandler

The file handler implementing the git:// protocol.

capellambse.filehandler.http.HTTPFileHandler

A simple http(s):// file handler.

activate_viewpoint(name, version)
Return type:

None

Parameters:
by_uuid(uuid)

Search the entire model for an element with the given UUID.

Return type:

Any

Parameters:

uuid (str)

property description_badge: str

Describe model contents distribution with an SVG badge.

diagram_cache: FileHandler | None
diagrams

The diagrams of this MelodyModel.

enumeration_property_types()
Return type:

ElementList[EnumerationPropertyType]

property filtering_model

Return a callable object that fetches the given attribute(s) from its operand. After f = attrgetter(‘name’), the call f(r) returns r.name. After g = attrgetter(‘name’, ‘date’), the call g(r) returns (r.name, r.date). After h = attrgetter(‘name.first’, ‘name.last’), the call h(r) returns (r.name.first, r.name.last).

find_references(target, /)

Search the model for references to the given object.

Parameters:

target (ModelObject | str) – The target object to search for.

Yields:

tuple[ModelObject, str, int | None] – A 3-tuple containing the referencing model object, the attribute on that object, and an optional index. If the attribute contains a list of objects, the index shows the index into the list that was found. Otherwise the index is None.

Return type:

Iterator[tuple[Any, str, int | None]]

property info: ModelInfo
property la: LogicalArchitecture
property name: str

The name of this model.

property oa: OperationalAnalysis
property pa: PhysicalArchitecture
property project: Project
property_value_packages()
Return type:

ElementList[PropertyValuePkg]

property pvmt: PVMTConfiguration
referenced_viewpoints()
Return type:

dict[str, str]

property resources: dict[str, FileHandler]
property sa: SystemAnalysis
save(**kw)

Save the model back to where it was loaded from.

Parameters:

kw (Any) – Additional keyword arguments accepted by the file handler in use. Please see the respective documentation for more info.

Return type:

None

See also

capellambse.filehandler.localfilehandler.LocalFileHandler.write_transaction

Accepted **kw when using local directories

capellambse.filehandler.git.GitFileHandler.write_transaction

Accepted **kw when using git:// and similar URLs

Notes

With a file handler that contacts a remote location (such as the GitFileHandler with non-local repositories), saving might fail if the local state has gone out of sync with the remote state. To avoid this, always leave the update_cache parameter at its default value of True if you intend to save changes.

search(*xtypes, below=None)

Search for all elements with any of the given xsi:types.

If only one xtype is given, the return type will be ElementList, otherwise it will be MixedElementList.

If no xtypes are given at all, this method will return an exhaustive list of all (semantic) model objects that have an xsi:type set.

Parameters:
  • xtypes (str | type[ModelObject]) – The xsi:types to search for, or the classes corresponding to them (or a mix of both).

  • below (ModelElement | None) – A model element to constrain the search. If given, only those elements will be returned that are (immediate or nested) children of this element. This option takes into account model fragmentation, but it does not treat link elements specially.

Return type:

ElementList

update_diagram_cache(capella_cli, image_format='svg', *, create_index=False, force=None, background=True)

Update the diagram cache if one has been specified.

If a diagram_cache has been specified while loading a Capella model it will be updated when this function is called.

The diagram cache will be populated by executing the Capella function “Export representations as images” which is normally accessible via the context menu of an .aird node in Capella’s project explorer. The export of diagrams happens with the help of Capella’s command line interface (CLI).

The CLI of Capella must be specified by the caller. It is possible to work with a local installation or a Docker image of an individual Capella bundle.

At the moment it is supported to run a Docker image using the container system Docker and the docker executable must be in the PATH environment variable.

Parameters:
  • capella_cli (str) –

    The Capella CLI to use when exporting diagrams from the given Capella model. The provided string can come with a "{VERSION}" placeholder. If specified, this placeholder will be replaced by the x.y.z formatted version of Capella that has been used when the given Capella model was last saved. After consideration of the optional placeholder this function will first check if the value of capella_cli points to a local Capella executable (that can be an absolute path or an executable/ symbolic link that has been made available via the environment variable PATH). If no executable can be found it is expected that capella_cli represents a Docker image name for an image that behaves like the Capella CLI. For the case of passing a Docker image name through capella_cli this means it is assumed that something like the following

    docker run --rm -it <capella_cli> -nosplash \
        -consolelog -app APP -appid APPID
    

    will work. The parameter force can be set to change the described behaviour and force the function to treat the capella_cli as a local executable or a Docker image only.

  • image_format (Literal['bmp', 'gif', 'jpg', 'png', 'svg']) – Format of the image file(s) for the exported diagram(s). This can be set to any value out of "bmp", "gif", "jpg", "png", or "svg".

  • create_index (bool) –

    If True, two index files index.json and index.html will be created. The JSON file consists of a list of dictionaries, each representing a diagram in the model. The dictionaries come with the keys

    • uuid: The unique ID of the diagram

    • name: Name of the diagram as it has been set in Capella

    • type: The diagram type as it was created in Capella

    • viewpoint: The source layer from where the representation is loaded from. It is Common for layerless diagrams.

    • success: A boolean stating if a diagram has been exported from Capella

    The HTML file shows a numbered list of diagram names which are hyperlinked to the diagram image file. Right beside a diagram’s name one can also see the diagram’s UUID in a discreet light gray and tiny font size. The HTML index also provides some meta data like a timestamp for the update of diagrams.

  • force (Optional[Literal['docker', 'exe']]) – If the value of capella_cli is ambiguous and can match both a local executable and a Docker image, this parameter can be used to bypass the auto-detection and force the choice. A value of "exe" always interprets capella_cli as local executable, "docker" always interprets it as a docker image name. None (the default) enables automatic detection.

  • background (bool) –

    Add a white background to exported SVG images.

    Ignored if the image_format is not "svg".

Return type:

None

Examples

Running a local installation of Capella

All the following examples call the method update_diagram_cache() on a model for which a diagram cache has been specified, example:

>>> import capellambse
>>> model = capellambse.MelodyModel(
...    "/path/to/model.aird",
...    diagram_cache="/path/to/diagram_cache",
... )

Passing an executable/ symlink named capella that is in the PATH environment variable:

>>> model.update_diagram_cache(
...     "capella", "png", True
... )

Passing an absolute path to a local installation of Capella that contains the Capella version:

>>> model.update_diagram_cache(
...     "/Applications/Capella_{VERSION}.app/Contents/MacOS/capella"
... )

Running a Capella container

>>> model.update_diagram_cache(
...     "ghcr.io/dsd-dbs/capella-dockerimages/capella/base"
...     ":{VERSION}-selected-dropins-main"
... )
property uuid: str

The unique ID of the model’s root element.

property validate
property validation: None

Provides access to the model’s validation rules and results.

class capellambse.model.MixedElementList

Bases: ElementList[ModelElement]

ElementList that handles proxies using XTYPE_HANDLERS.

__init__(model, elements, elemclass=None, **kw)

Create a MixedElementList.

Parameters:
  • model (MelodyModel) – The model that all elements are a part of.

  • elements (list[_Element]) – The members of this list.

  • elemclass (Any) – Ignored; provided for drop-in compatibility.

  • **kw (Any) – Additional arguments are passed to the superclass.

Return type:

None

class capellambse.model.ModelElement

Bases: object

A model element.

This is the common base class for all elements of a model. In terms of the metamodel, it combines the role of modellingcore.ModelElement and all its superclasses; references to any superclass should be modified to use this class instead.

__init__(model, parent, xmltag=None, /, *, uuid, **kw)
Parameters:
Return type:

None

_get_icon(format, /, *, size=16)

Render a small icon for this object.

Parameters:
Return type:

Any | None

This is the same icon that is also used in diagrams.

Parameters:
  • format (str) –

    The format to use.

    This uses the same format conversion machinery as diagrams, but starts with the svg format. This means that svg and every format directly or indirectly derived from it are supported, including png, datauri_svg and others.

  • size (int) – Return the icon scaled to this horizontal and vertical size in pixels. This may yield higher quality results compared to scaling the returned icon, especially when using raster image formats.

Returns:

The icon (usually as str or bytes object), or None if no icon could be found.

Return type:

Any | None

_get_styleclass()

Return the styleclass of this object.

Return type:

str

The styleclass determines which set of styles gets applied when drawing this object in a diagram.

Return type:

str

applied_property_value_groups

The applied property value groups of this ModelElement.

applied_property_values

The applied property values of this ModelElement.

constraints: Accessor

The constraints of this ModelElement.

description

A POD containing a string with HTML inside.

property diagrams
filtering_criteria

The filtering criteria of this ModelElement.

classmethod from_model(model, element)

Wrap an existing model object.

Parameters:
  • model (MelodyModel) – The MelodyModel instance

  • element (_Element) – The XML element to wrap

Returns:

An instance of ModelElement (or a more appropriate subclass, if any) that wraps the given XML element.

Return type:

ModelElement

property layer: ComponentArchitecture

Find the layer that this element belongs to.

Note that an architectural layer normally does not itself have a parent layer.

Raises:

AttributeError – Raised if this element is not nested below a layer.

name

A POD containing arbitrary string data.

parent: ParentAccessor

A ParentAccessor that was not properly configured. Ensure that __set_name__ gets called after construction.

property progress_status: str
property_value_groups

The property value groups of this ModelElement.

property_value_packages: Accessor

The property value packages of this ModelElement.

property_values

The property values of this ModelElement.

pvmt

The pvmt of this ModelElement.

requirements

The requirements of this ModelElement.

sid

The unique system identifier of this object.

summary

A POD containing arbitrary string data.

traces

The traces of this ModelElement.

uuid

The universally unique identifier of this object.

This attribute is automatically populated when the object is instantiated, and cannot be changed afterwards. It is however possible to specify the UUID when instantiating the object, in which case it will be used instead of generating a new one.

The UUID may be used in hashmaps and the like, as it is guaranteed to not change during the object’s lifetime and across model save/reload cycles.

property validate
validation

The validation of this ModelElement.

property visible_on_diagrams
property xtype
class capellambse.model.ModelInfo

Bases: ModelInfo

ModelInfo(url: ‘str | None’, title: ‘str | None’, entrypoint: ‘pathlib.PurePosixPath’, resources: ‘dict[str, filehandler.abc.HandlerInfo]’, capella_version: ‘str’, viewpoints: ‘dict[str, str]’, diagram_cache: ‘filehandler.abc.HandlerInfo | None’)

__init__(url, title, entrypoint, resources, capella_version, viewpoints, diagram_cache)
Parameters:
Return type:

None

diagram_cache: HandlerInfo | None
class capellambse.model.ModelObject

Bases: Protocol

A class that wraps a specific model object.

Most of the time, you’ll want to subclass the concrete ModelElement class. However, some special classes (e.g. AIRD diagrams) provide a compatible interface, but it doesn’t make sense to wrap a specific XML element. This protocol class is used in type annotations to catch both “normal” ModelElement subclasses and the mentioned special cases.

__init__(model, parent, xmltag, /, **kw)

Create a new model object.

Parameters:
  • model (MelodyModel) – The model instance.

  • parent (_Element) – The parent XML element below which to create a new object.

  • xmltag (str | None) – Override the XML tag to use for this element.

  • kw (Any) – Any additional arguments will be used to populate the instance attributes. Note that some attributes may be required by specific element types at construction time (commonly e.g. uuid).

Return type:

None

classmethod from_model(model, element)

Instantiate a ModelObject from existing model elements.

Return type:

ModelObject

Parameters:
class capellambse.model.NewObject

Bases: object

A marker which will create a new model object when inserted.

This object can be assigned to an attribute of a model object, and will be replaced with a new object of the correct type by the attribute’s accessor.

For the time being, client code should treat this as opaque object.

__init__(type_hint, **kw)
Parameters:
Return type:

None

exception capellambse.model.NonUniqueMemberError

Bases: ValueError

Raised when a duplicate member is inserted into a list.

property attr
property parent
property target
class capellambse.model.ParentAccessor

Bases: PhysicalAccessor[T_co]

Accesses the parent XML element.

__init__(class_=None)
Parameters:

class_ (type[T_co] | None)

class capellambse.model.PhysicalAccessor

Bases: Accessor[T_co]

Helper super class for accessors that work with real elements.

__init__(class_, xtypes=None, *, aslist=None, mapkey=None, mapvalue=None, fixed_length=0)
Parameters:
Return type:

None

aslist: type[ElementList] | None
class_: type[TypeVar(T_co, bound= ModelObject, covariant=True)]
list_extra_args: Mapping[str, Any]
xtypes: Set[str]
class capellambse.model.PhysicalLinkEndsAccessor

Bases: Association[T_co]

__init__(class_, attr, *, aslist, mapkey=None, mapvalue=None)

Define an Association.

Associations are stored as simple links in an XML attribute.

Parameters:
  • class – The proxy class. Currently only used for type hints.

  • attr (str) – The XML attribute to handle.

  • aslist (type[ElementList]) – If None, the attribute contains at most one element reference, and either None or the constructed proxy will be returned. If not None, must be a subclass of ElementList. It will be used to return a list of all matched objects.

  • mapkey (str | None) –

    Specify the attribute to look up when the returned list is indexed with a str. If not specified, str indexing is not possible.

    Ignored if aslist is not specified.

  • mapvalue (str | None) –

    If specified, return this attribute of the found object when using str indices into the returned list. If not specified, the found object itself is returned.

    Ignored if aslist is not specified.

  • fixed_length

    When non-zero, the returned list will try to stay at exactly this length, by not allowing to insert or delete beyond this many members.

    Ignored if aslist is not specified.

  • class_ (type[T_co])

Return type:

None

attr
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
class capellambse.model.S

TypeVar for “str | None”.

alias of TypeVar(‘S’, bound=str | None)

class capellambse.model.SpecificationAccessor

Bases: Accessor[_Specification]

Provides access to linked specifications.

class capellambse.model.StringPOD

Bases: BasePOD[str]

A POD containing arbitrary string data.

__init__(attribute, /, *, writable=True)

Create a StringPOD.

Parameters:
  • attribute (str) – The name of the attribute on the XML element.

  • writable (bool) – Whether to allow changing the value at runtime.

Return type:

None

class capellambse.model.T

TypeVar for “capellambse.model.ModelObject”.

alias of TypeVar(‘T’, bound=ModelObject)

class capellambse.model.T_co

Covariant TypeVar for “capellambse.model.ModelObject”.

alias of TypeVar(‘T_co’, bound=ModelObject, covariant=True)

class capellambse.model.TypecastAccessor

Bases: WritableAccessor[T_co], PhysicalAccessor[T_co]

Changes the static type of the value of another accessor.

This is useful for when a class has an attribute that is polymorphic, but the accessor should always return a specific subclass.

At runtime, this Accessor mostly behaves like a simple alias (without performing any runtime type checks or conversions). When creating new objects, it will only allow to create objects of the specified type.

__init__(cls, attr, mapkey=None, mapvalue=None)
Parameters:
Return type:

None

aslist: type[ElementListCouplingMixin] | None
class_: type[TypeVar(T_co, bound= ModelObject, covariant=True)]
create(elmlist, typehint=None, /, **kw)

Create and return a new element of type elmclass.

Parameters:
  • elmlist (ElementListCouplingMixin) – The (coupled) ElementList to insert the new object into.

  • typehint (str | None) – Hints for finding the correct type of element to create. Can either be a full or shortened xsi:type string, or an abbreviation defined by the specific Accessor instance.

  • kw (Any) – Initialize the properties of the new object. Depending on the object’s type, some attributes may be required.

Return type:

TypeVar(T_co, bound= ModelObject, covariant=True)

delete(elmlist, obj)

Delete the obj from the model.

Return type:

None

Parameters:
insert(elmlist, index, value)

Insert the value object into the model.

The object must be inserted at an appropriate place, so that, if elmlist were to be created afresh, value would show up at index index.

Return type:

None

Parameters:
list_extra_args: Mapping[str, Any]
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
xtypes: Set[str]
class capellambse.model.U

TypeVar (unbound).

alias of TypeVar(‘U’)

class capellambse.model.WritableAccessor

Bases: Accessor[T_co]

An Accessor that also provides write support on lists it returns.

__init__(*args, aslist, single_attr=None, **kw)
Parameters:
Return type:

None

aslist: type[ElementListCouplingMixin] | None
class_: type[TypeVar(T_co, bound= ModelObject, covariant=True)]
create(elmlist, typehint=None, /, **kw)

Create and return a new element of type elmclass.

Parameters:
  • elmlist (ElementListCouplingMixin) – The (coupled) ElementList to insert the new object into.

  • typehint (str | None) – Hints for finding the correct type of element to create. Can either be a full or shortened xsi:type string, or an abbreviation defined by the specific Accessor instance.

  • kw (Any) – Initialize the properties of the new object. Depending on the object’s type, some attributes may be required.

Return type:

TypeVar(T_co, bound= ModelObject, covariant=True)

create_singleattr(elmlist, arg, /)

Create an element that only has a single attribute of interest.

Return type:

TypeVar(T_co, bound= ModelObject, covariant=True)

Parameters:
delete(elmlist, obj)

Delete the obj from the model.

Return type:

None

Parameters:
insert(elmlist, index, value)

Insert the value object into the model.

The object must be inserted at an appropriate place, so that, if elmlist were to be created afresh, value would show up at index index.

Return type:

None

Parameters:
list_extra_args: Mapping[str, Any]
purge_references(obj, target)

Purge references to the given object from the model.

This method is called while deleting physical objects, in order to get rid of references to that object (and its descendants). Reference purging is done in two steps, which is why this method returns a context manager.

The first step, executed by the __enter__ method, collects references to the target and ensures that deleting them would result in a valid model. If any validity constraints would be violated, an exception is raised to indicate as such, and the whole operation is aborted.

Once all __enter__ methods have been called, the target object is deleted from the model. Then all __exit__ methods are called, which triggers the actual deletion of all previously discovered references.

As per the context manager protocol, __exit__ will always be called after __enter__, even if the operation is to be aborted. The __exit__ method must therefore inspect whether an exception was passed in or not in order to know whether the operation succeeded.

In order to not confuse other context managers and keep the model consistent, __exit__ must not raise any further exceptions. Exceptions should instead be logged to stderr, for example by using the logging.Logger.exception() facility.

The purge_references method will only be called for Accessor instances that actually contain a reference.

Parameters:
  • obj (ModelObject) – The model object to purge references from.

  • target (ModelObject) – The object that is to be deleted; references to this object will be purged.

Returns:

A context manager that deals with purging references in a transactional manner.

Return type:

contextlib.AbstractContextManager

Raises:
  • InvalidModificationError – Raised by the returned context manager’s __enter__ method if the attempted modification would result in an invalid model. Note that it is generally preferred to allow the operation and take the necessary steps to keep the model consistent, if possible. This can be achieved for example by deleting dependent objects along with the original deletion target.

  • Exception – Any exception may be raised before __enter__ returns in order to abort the transaction and prevent the obj from being deleted. No exceptions must be raised by __exit__.

Examples

A simple implementation for purging a single object reference could look like this:

@contextlib.contextmanager
def purge_references(self, obj, target):
    assert self.__get__(obj, type(obj)) == target

    yield

    try:
        self.__delete__(obj)
    except Exception:
        LOGGER.exception("Could not purge a dangling reference")
single_attr: str | None
capellambse.model.attr_equal(attr)
Return type:

Callable[[type[TypeVar(T, bound= ModelObject)]], type[TypeVar(T, bound= ModelObject)]]

Parameters:

attr (str)

capellambse.model.build_xtype(class_)
Return type:

str

Parameters:

class_ (type[ModelObject])

capellambse.model.find_wrapper(typehint)

Find the possible wrapper classes for the hinted type.

The typehint is either a single class name, or a namespace prefix and class name separated by :. This function searches for all known wrapper classes that match the given namespace prefix (if any) and which have the given name, and returns them as a tuple. If no matching wrapper classes are found, an empty tuple is returned.

Return type:

tuple[type[ModelObject], ...]

Parameters:

typehint (str)

capellambse.model.set_self_references(*args)
Return type:

None

Parameters:

args (tuple[type[ModelObject], str])

capellambse.model.stringy_enum(et)

Make an Enum stringy.

This decorator makes an Enum’s members compare equal to their respective name.

Return type:

type[Enum]

Parameters:

et (type[Enum])

capellambse.model.xtype_handler(arch=None, /, *xtypes)

Register a class as handler for a specific xsi:type.

arch is the xsi:type of the desired architecture. It must always be a simple string or None. In the latter case the definition applies to all elements regardless of their architectural layer. Architecture-specific definitions will always win over architecture-independent ones.

Each string given in xtypes notes an xsi:type of elements that this class handles. It is possible to specify multiple values, in which case the class will be registered for each xsi:type under the architectural layer given in arch.

Handler classes’ __init__ methods must accept two positional arguments. The first argument is the MelodyModel instance which loaded the corresponding model, and the second one is the LXML element that needs to be handled.

Example:

>>> @xtype_handler(None, 'xtype:1', 'xtype:2')
... class Test:
...     _xmltag = "ownedTests"
...     def from_model(self, model, element, /):
...         ...  # Instantiate from model XML element
Return type:

Callable[[type[TypeVar(T, bound= ModelObject)]], type[TypeVar(T, bound= ModelObject)]]

Parameters:
  • arch (str | None)

  • xtypes (str)

Submodules

capellambse.model.diagram module

Classes that allow access to diagrams in the model.

class capellambse.model.diagram.AbstractDiagram

Bases: object

Abstract superclass of model diagrams.

Also directly exposed as capellambse.model.AbstractDiagram.

__init__(model)
Parameters:

model (MelodyModel)

Return type:

None

_allow_render: bool = True

Allow this diagram to be rendered by the internal rendering engine.

If this property is set to False, and a diagram cache was specified for the model, this diagram can only be loaded from the cache, and will never be rendered. Has no effect if there was no diagram cache specified.

abstract _create_diagram(params)

Perform the actual rendering of the diagram.

This method is called by render() to perform the actual rendering of the diagram. It is passed the parameters that were passed to render() as a dictionary.

Subclasses override this method to implement their rendering logic. Do not call this method directly, use render() instead - it will take care of caching and properly converting the render output.

Return type:

Diagram

Parameters:

params (dict[str, Any])

filters: MutableSet[str]

The filters that are activated for this diagram.

invalidate_cache()

Reset internal diagram cache.

Return type:

None

name: str

Human-readable name for this diagram.

property nodes: MixedElementList

Return a list of all nodes visible in this diagram.

render(fmt, /, *, pretty_print=False, **params)

Render the diagram in the given format.

Parameters:
  • fmt (str | None) –

    The output format to use.

    If None, the Diagram is returned without format conversion.

  • pretty_print (bool) – Whether to pretty-print the output. Only applies to text-based formats. Ignored if the output format converter does not support pretty-printing.

  • params – Additional render parameters. Which parameters are supported depends on the specific type of diagram.

Return type:

Any

save(file, fmt, /, *, pretty_print=False, **params)

Render the diagram and write it to a file.

Parameters:
  • file (Union[str, PathLike, IO[bytes], None]) –

    The file to write the diagram to. Can be a filename, or a file-like object in binary mode.

    Text-based formats that render to a str will always be encoded as UTF-8.

    If None is passed, and the selected format has a known filename extension, a filename will be generated from the diagram’s name and the extension.

  • fmt (str) – The output format to use.

  • pretty_print (bool) – Whether to pretty-print the output. Only applies to text-based formats. Ignored if the output format converter does not support pretty-printing.

  • params – Additional render parameters to pass to the render() call.

Return type:

None

target: ModelElement

This diagram’s “target”.

The target of a diagram is usually:

  • The model element which is the direct parent of all visible nodes OR

  • The only top-level element in the diagram OR

  • The element which is considered to be the “element of interest”.

uuid: str

Unique ID of this diagram.

class capellambse.model.diagram.ConfluenceSVGFormat

Bases: object

Convert the diagram to Confluence-style SVG.

classmethod convert(dg)
Return type:

str

Parameters:

dg (str)

classmethod convert_pretty(dg)
Return type:

str

Parameters:

dg (str)

depends

alias of SVGFormat

postfix = ']]></ac:plain-text-body></ac:structured-macro>'
prefix = '<ac:structured-macro ac:macro-id="4239b681-1087-4a46-a9db-9d455bdaca67" ac:name="html" ac:schema-version="1"><ac:plain-text-body><![CDATA['
class capellambse.model.diagram.Diagram

Bases: AbstractDiagram

Provides access to a single diagram.

Also directly exposed as capellambse.model.Diagram.

__init__(**kw)
Parameters:

kw (Any)

Return type:

None

property _allow_render: bool

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

_create_diagram(params)

Perform the actual rendering of the diagram.

This method is called by render() to perform the actual rendering of the diagram. It is passed the parameters that were passed to render() as a dictionary.

Subclasses override this method to implement their rendering logic. Do not call this method directly, use render() instead - it will take care of caching and properly converting the render output.

Return type:

Diagram

Parameters:

params (dict[str, Any])

description

A POD containing a string with HTML inside.

property filters: MutableSet[str]

Return a set of currently activated filters on this diagram.

classmethod from_model(model, element)

Wrap a diagram already defined in the Capella AIRD.

Return type:

Diagram

Parameters:
invalidate_cache()

Reset internal diagram cache.

Return type:

None

name: str

Human-readable name for this diagram.

property nodes: MixedElementList

Return a list of all nodes visible in this diagram.

property representation_path: str

The ID of the representation, i.e. the actual diagram.

Capella distinguishes between the representation (which contains all visual data) and a representation descriptor, which only contains a handful of metadata like the diagram name and description. Both have their own IDs, and the descriptor contains a link to the representation.

property semantic_nodes: MixedElementList
property target: ModelElement
property type: DiagramType

Return the type of this diagram.

uuid: str

Unique ID of this diagram.

property viewpoint: str
property xtype
class capellambse.model.diagram.DiagramAccessor

Bases: Accessor

Provides access to a list of diagrams below the specified viewpoint.

Also directly exposed as capellambse.model.DiagramAccessor.

__init__(viewpoint=None, *, cacheattr=None)
Parameters:
  • viewpoint (str | None)

  • cacheattr (str | None)

Return type:

None

class capellambse.model.diagram.DiagramFormat

Bases: Protocol

__init__(*args, **kwargs)
classmethod convert(dg)
Return type:

Any

Parameters:

dg (Any)

class capellambse.model.diagram.DiagramType

Bases: Enum

The types of diagrams that Capella knows about.

Extracted from:

$CAPELLA/eclipse/configuration/org.eclipse.osgi/635/0/.cp/description

with:

grep '<ownedRepresentations' *(.)         | grep --color=always -P '(?<=name=").*?(?=")'

Also directly exposed as capellambse.model.DiagramAccessor.

CC = 'Contextual Capability'
CDB = 'Class Diagram Blank'
CDI = 'Contextual Component Detailed Interfaces'
CEI = 'Contextual Component External Interfaces'
CIBD = 'Configuration Items Breakdown'
CII = 'Contextual Component Internal Interfaces'
CM = 'Contextual Mission'
COC = 'Contextual Operational Capability'
CRB = 'Capability Realization Blank'
CRI = 'Contextual Capability Realization Involvement'
CRR = 'Capability Realization Refinement'
CSA = 'Contextual System Actors'
EAB = 'EPBS Architecture Blank'
ES = 'Component Exchanges Scenario'
FS = 'Functional Scenario'
ID = 'Interface Delegations'
IDB = 'Interfaces Diagram Blank'
IS = 'Component Interfaces Scenario'
LAB = 'Logical Architecture Blank'
LCBD = 'Logical Component Breakdown'
LDFB = 'Logical Data Flow Blank'
LFBD = 'Logical Function Breakdown'
LFCD = 'Functional Chain Description'
MB = 'Missions Blank'
MCB = 'Missions Capabilities Blank'
MSM = 'Mode State Machine'
OAB = 'Operational Entity Blank'
OABD = 'Operational Activity Breakdown'
OAIB = 'Operational Activity Interaction Blank'
OAS = 'Activity Interaction Scenario'
OCB = 'Operational Capabilities Blank'
OEBD = 'Operational Entity Breakdown'
OES = 'Operational Interaction Scenario'
OPD = 'Operational Process Description'
ORB = 'Operational Role Blank'
PAB = 'Physical Architecture Blank'
PCBD = 'Physical Component Breakdown'
PD = 'Package Dependencies'
PDFB = 'Physical Data Flow Blank'
PFBD = 'Physical Function Breakdown'
PFCD = 'Functional Chain Description'
PPD = 'Physical Path Description'
SAB = 'System Architecture Blank'
SDFB = 'System Data Flow Blank'
SFBD = 'System Function Breakdown'
SFCD = 'Functional Chain Description'
UNKNOWN = '(Unknown Diagram Type)'
class capellambse.model.diagram.PNGFormat

Bases: object

Convert the diagram to PNG.

static convert(dg)
Return type:

bytes

Parameters:

dg (str)

depends

alias of SVGFormat

filename_extension = '.png'
static from_cache(cache)
Return type:

bytes

Parameters:

cache (bytes)

mimetype = 'image/png'
class capellambse.model.diagram.PrettyDiagramFormat

Bases: DiagramFormat, Protocol

classmethod convert_pretty(dg)
Return type:

Any

Parameters:

dg (Any)

capellambse.model.diagram.REPR_DRAW: bool = False

Whether to draw diagrams onto the terminal in their repr().

Determined automatically based on whether output is connected to a terminal, and whether the terminal supports the kitty graphics protocol.

class capellambse.model.diagram.SVGDataURIFormat

Bases: object

classmethod convert(dg)
Return type:

str

Parameters:

dg (str)

depends

alias of SVGFormat

preamble = 'data:image/svg+xml;base64,'
class capellambse.model.diagram.SVGFormat

Bases: object

Convert the diagram to SVG.

static convert(dg)
Return type:

str

Parameters:

dg (SVGDiagram)

static convert_pretty(dg)
Return type:

str

Parameters:

dg (SVGDiagram)

depends()

Convert the diagram to a SVGDiagram.

Return type:

SVGDiagram

Parameters:

dg (Diagram)

filename_extension = '.svg'
static from_cache(cache)
Return type:

str

Parameters:

cache (bytes)

mimetype = 'image/svg+xml'
class capellambse.model.diagram.SVGInHTMLIMGFormat

Bases: object

static convert(dg)
Return type:

Markup

Parameters:

dg (str)

depends

alias of SVGDataURIFormat

class capellambse.model.diagram.TerminalGraphicsFormat

Bases: object

The kitty terminal graphics protocol diagram format.

This graphics format generates terminal escape codes that transfer PNG data to a TTY using the kitty graphics protocol.

classmethod convert(dg)
Return type:

bytes

Parameters:

dg (bytes)

depends

alias of PNGFormat

static is_supported()

Return whether the used terminal supports graphics.

This implementation checks whether stdin, stdout and stderr are connected to a terminal, and whether the $TERM environment variable is set to a know-supportive value. Currently the only recognized value is xterm-kitty.

Return type:

bool

exception capellambse.model.diagram.UnknownOutputFormat

Bases: ValueError

An unknown output format was requested for the diagram.

capellambse.model.diagram.convert_format(sourcefmt, targetfmt, data, /, *, pretty_print=False)

Convert between different image formats.

Parameters:
  • sourcefmt (str | None) – Name of the current format. If None, the current format is a capellambse.diagram.Diagram object.

  • targetfmt (str) – Name of the target format.

  • data (Any) – Image data in the format produced by the “sourcefmt” converter.

  • pretty_print (bool) – Whether to instruct the converters to pretty-print their output. Only relevant for text-based formats like SVG.

Returns:

The converted image data.

Return type:

Any

Raises:

ValueError – Raised if either format is not known, or if no converter chain could be built to convert between the two formats.

capellambse.model.diagram.convert_svgdiagram(dg)

Convert the diagram to a SVGDiagram.

Return type:

SVGDiagram

Parameters:

dg (Diagram)