Trailing Objects#
- class umbrella.trailing_objects.TrailingObjects(**kwargs)[source]#
Python implementation of TrailingObjects found in the Swift ABI.
This class uses typing to inspect annotated types and create trailer information based on them. You can think of “trailing objects” when using this class, for instance:
>>> @dataclass ... class Foo: ... a: int = csfield(Int32ul) ...
Now, we want to have additional trailing objects based on runtime conditions at the end of each
Foo
object. We now create another class that stores our new “trailing” information:>>> @dataclass ... class Bar: ... x: int = csfield(Int32ul) ...
By annotating the previously defined class Foo with this class, one or multiple Bar objects will be placed as trailing objects at the end of each Foo instance virtually.
>>> @dataclass ... class Foo(TrailingObjects[Bar]): ... a: int = csfield(Int32ul) ... # in order to get the amount of trailing Bar objects, a function ... # must be defined, otherwise 1 is used ... def _num_bar(self) -> int: ... return self.a
Each trailing object can be retrieved by calling
getTrailingObject(s)
. The return value will be a tuple or single value based on the provided count.>>> foo = Foo(a=2) # retrieve Foo instance >>> foo.getTrailingObjects(Bar) (Bar(x=1), Bar(x=2)) >>> foo.getTrailingObject(Bar) Bar(x=1)
The amount of trailing objects will be computed per type. Each type may have a method mapped to it. The naming convention of each method is as follows:
>>> nameof(Foo) '_num_foo' >>> nameof(FooBar) '_num_foo_bar'
The classes defined above can be displayed virtually as follows:
0 4 4 8 8 12 ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Foo │ │ Bar │ │ Bar │ ├──────────┤ ├──────────┤ ├──────────┤ │ uint32 a │ │ uint32 x │ │ uint32 x │ └──────────┘ └──────────┘ └──────────┘ ▲ ▲ └──────────────────────────┘ Amount == Foo.a
- getTrailingObject(token: Type[T]) T | None [source]#
Retrieves a single trailing object based on the provided token.
- Parameters:
token (Token[T]) – the token annotated with the trailing type
- Returns:
the parsed trailing object
- Return type:
t.Optional[T]
- getTrailingObjects(token: Type[T]) Tuple[T] | None [source]#
Retrieves one or multiple trailing objects.
If a trailing object is optional, the count should be set to zero, which in result leads to a null value returned by this method.
- Parameters:
token (Token[T]) – the token annotated with the trailing type
- Raises:
TypeError – if the provided type is not present in the defined trailing objects
- Returns:
the parsed objects as tuple (always as tuple)
- Return type:
t.Optional[t.Tuple[T]]