Coverage for /home/jenkins/workspace/NDS/Zserio/NDS_ZSERIO-linux-build/compiler/extensions/python/runtime/src/zserio/cppbind.py: 100%
20 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-12-13 15:12 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2023-12-13 15:12 +0000
1"""
2The module provides helper for importing of optimized C++ classes.
3"""
5import importlib
6import os
7import typing
9ZSERIO_PYTHON_IMPLEMENTATION_ENV = "ZSERIO_PYTHON_IMPLEMENTATION"
10ZSERIO_CPP_MODULE = "zserio_cpp"
12def import_cpp_class(cppname: str, *, exception_class = None) -> typing.Optional[typing.Type[typing.Any]]:
13 """
14 Tries to import optimized C++ implementation of the given python class if 'ZSERIO_PYTHON_IMPLEMENTATION'
15 environment variable is either unset or set to 'cpp'.
17 Depending on the content of the 'ZSERIO_PYTHON_IMPLEMENTATION' environment variable,
18 it either fails when no C++ implementation is available ('cpp') or ignores missing implementation
19 and just return the original python class (None) or even does not try to load the C++ implementation if
20 the variable is set to anyhing else (e.g. 'python').
22 :param pyclass: Pure python class implemenation for which the C++ optimized version should be loaded.
23 :param cppname: Name of optimized C++ class in case that it differs from the pyclass name.
24 :param exception_class: Exception to raise in case of an error.
25 :returns: Requested implemenation of the given pyclass.
26 :raises PythonRuntimeException: When the requested implementation is not available.
27 """
29 if exception_class is None:
30 # we need to break cyclic import from zserio.exception
31 # pylint: disable-next=cyclic-import,import-outside-toplevel
32 from zserio.exception import PythonRuntimeException
33 exception_class = PythonRuntimeException
35 impl = os.getenv(ZSERIO_PYTHON_IMPLEMENTATION_ENV)
36 if not impl in [None, "python", "cpp", "c++"]:
37 raise exception_class(f"Zserio Python runtime implementation '{impl}' is not available!")
39 if impl != "python":
40 try:
41 return getattr(importlib.import_module(ZSERIO_CPP_MODULE), cppname)
42 except (ImportError, AttributeError) as err:
43 if impl in ["cpp", "c++"]:
44 message = f"Zserio C++ implementation of '{cppname}' is not available!"
45 raise exception_class(message) from err
46 return None