From 75a109419cc8b777d740208fd1d0f0c0ad7932aa Mon Sep 17 00:00:00 2001 From: Harald Welte Date: Tue, 23 Jul 2024 10:13:57 +0200 Subject: [PATCH] pySim.tlv: Add convenience methods to IE class The new methods allow programmatic resolution of nested IEs from a parent, assuming there's only one child of a given type (which is often but not always the case). Change-Id: Ic95b74437647ae8d4bf3cdc481832afb622e3cf0 --- pySim/tlv.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/pySim/tlv.py b/pySim/tlv.py index 6dc5301d..ed3be5d7 100644 --- a/pySim/tlv.py +++ b/pySim/tlv.py @@ -19,7 +19,7 @@ import inspect import abc import re -from typing import List, Tuple +from typing import List, Tuple, Optional from pySim.utils import bertlv_encode_len, bertlv_parse_len, bertlv_encode_tag, bertlv_parse_tag from pySim.utils import comprehensiontlv_encode_tag, comprehensiontlv_parse_tag @@ -189,6 +189,24 @@ class IE(Transcodable, metaclass=TlvMeta): self.children = [] return super().from_bytes(do, context=context) + def child_by_name(self, name: str) -> Optional['IE']: + """Return a child IE instance of given snake-case/json type name. This only works in case + there is no more than one child IE of the given type.""" + children = list(filter(lambda c: camel_to_snake(type(c).__name__) == name, self.children)) + if len(children) > 1: + raise KeyError('There are multiple children of class %s' % name) + elif len(children) == 1: + return children[0] + + def child_by_type(self, cls) -> Optional['IE']: + """Return a child IE instance of given type (class). This only works in case + there is no more than one child IE of the given type.""" + children = list(filter(lambda c: isinstance(c, cls), self.children)) + if len(children) > 1: + raise KeyError('There are multiple children of class %s' % cls) + elif len(children) == 1: + return children[0] + class TLV_IE(IE): """Abstract base class for various TLV type Information Elements."""