Skip to content

Commit 92e92f1

Browse files
committed
Add _make_repr to ir_to_ctypes
1 parent b7aa080 commit 92e92f1

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

pylibbpf/ir_to_ctypes.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,19 @@ def ir_type_to_ctypes(ir_type):
3838
raise TypeError(f"Unsupported IR type: {ir_type}")
3939

4040

41+
def _make_repr(struct_name: str, fields: list):
42+
"""Create a __repr__ function for a struct"""
43+
44+
def __repr__(self):
45+
field_strs = []
46+
for field_name, _ in fields:
47+
value = getattr(self, field_name)
48+
field_strs.append(f"{field_name}={value}")
49+
return f"<{struct_name} {' '.join(field_strs)}>"
50+
51+
return __repr__
52+
53+
4154
def convert_structs_to_ctypes(structs_sym_tab) -> Dict[str, Type[ctypes.Structure]]:
4255
"""Convert PythonBPF's structs_sym_tab to ctypes.Structure classes."""
4356
if not structs_sym_tab:
@@ -52,20 +65,16 @@ def convert_structs_to_ctypes(structs_sym_tab) -> Dict[str, Type[ctypes.Structur
5265
field_ctypes = ir_type_to_ctypes(field_ir_type)
5366
fields.append((field_name, field_ctypes))
5467

68+
repr_func = _make_repr(struct_name, fields)
69+
5570
struct_class = type(
5671
struct_name,
5772
(ctypes.Structure,),
5873
{
5974
"_fields_": fields,
6075
"__module__": "pylibbpf.ir_to_ctypes",
6176
"__doc__": f"Auto-generated ctypes structure for {struct_name}",
62-
"__repr__": lambda self: (
63-
f"<{struct_name} "
64-
+ " ".join(
65-
f"{name}={getattr(self, name)}" for name, _ in fields
66-
)
67-
+ ">"
68-
),
77+
"__repr__": repr_func,
6978
},
7079
)
7180

0 commit comments

Comments
 (0)