AbstractNativeType

Source code in cstruct/native_types.py
110
111
112
113
114
115
116
117
class AbstractNativeType(metaclass=NativeTypeMeta):
    def __str__(self) -> str:
        return self.type_name

    @classmethod
    def sizeof(cls) -> int:
        "Type size (in bytes)"
        return cls.__size__

sizeof() classmethod

Type size (in bytes)

cstruct/native_types.py
114
115
116
117
@classmethod
def sizeof(cls) -> int:
    "Type size (in bytes)"
    return cls.__size__

NativeTypeMeta

Bases: ABCMeta

Source code in cstruct/native_types.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class NativeTypeMeta(ABCMeta):
    __size__: int = 0
    " Size in bytes "
    type_name: str = ""
    " Type name "
    native_format: str = ""
    " Type format "

    def __new__(metacls: Type[type], name: str, bases: Tuple[str], namespace: Dict[str, Any]) -> Type[Any]:
        if namespace.get("native_format"):
            native_format = namespace["native_format"]
            namespace["__size__"] = struct.calcsize(native_format)
        else:
            native_format = None
            namespace["native_format"] = None
            namespace["__size__"] = None
        new_class: Type[Any] = super().__new__(metacls, name, bases, namespace)
        if namespace.get("type_name"):
            NATIVE_TYPES[namespace["type_name"]] = new_class
        return new_class

    def __len__(cls) -> int:
        "Type size (in bytes)"
        return cls.__size__

    @property
    def size(cls) -> int:
        "Type size (in bytes)"
        return cls.__size__

__size__: int = 0 class-attribute instance-attribute

Size in bytes

native_format: str = '' class-attribute instance-attribute

Type format

size: int property

Type size (in bytes)

type_name: str = '' class-attribute instance-attribute

Type name

__len__()

Type size (in bytes)

cstruct/native_types.py
100
101
102
def __len__(cls) -> int:
    "Type size (in bytes)"
    return cls.__size__

get_native_type(type_)

Get a base data type by name

Parameters:
  • type_ (str) –

    data type

Returns:
Raises:
  • KeyError

    If type is not defined

cstruct/native_types.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def get_native_type(type_: str) -> "AbstractNativeType":
    """
    Get a base data type by name

    Args:
        type_: data type

    Returns:
        class: data type class

    Raises:
        KeyError: If type is not defined
    """
    try:
        return NATIVE_TYPES[type_]
    except KeyError:
        raise KeyError(f"Unknown type `{type_}`")