Skip to content

Commit 61888cf

Browse files
committed
Add Python Metadata API improvements for handling Metadata as values, dictionary item assignment, and array appending. (skip-ci)
1 parent 0f69b1b commit 61888cf

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

python/metadata.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,14 @@ def __init__(
3434
handle: Optional[core.BNMetadata] = None
3535
):
3636
"""
37-
The 'raw' parameter is no longer needed it was a work around for a python 2 limitation.
38-
To pass raw data into this api simply use a `bytes` object
37+
The 'raw' parameter is no longer needed it was a workaround for a Python 2 limitation.
38+
To pass raw data into this API, simply use a `bytes` object.
3939
"""
4040
if handle is not None:
4141
self.handle = handle
42+
elif isinstance(value, Metadata):
43+
# If the value is already a Metadata object, reuse its handle
44+
self.handle = value.handle
4245
elif isinstance(value, bool):
4346
self.handle = core.BNCreateMetadataBooleanData(value)
4447
elif isinstance(value, int):
@@ -64,7 +67,7 @@ def __init__(
6467
md = Metadata(value[elm], signed, raw)
6568
core.BNMetadataSetValueForKey(self.handle, str(elm), md.handle)
6669
else:
67-
raise ValueError(f"{type(value)} doesn't contain type of: int, bool, str, float, list, dict")
70+
raise ValueError(f"{type(value)} is not a supported type: int, bool, str, bytes, float, list, tuple, dict, or Metadata")
6871

6972
def __len__(self):
7073
if self.is_array or self.is_dict or self.is_string or self.is_bytes:
@@ -146,6 +149,14 @@ def __getitem__(self, value):
146149

147150
raise NotImplementedError("Metadata object doesn't support indexing")
148151

152+
def __setitem__(self, key, value):
153+
if not self.is_dict:
154+
raise TypeError("Metadata object is not a dictionary and does not support item assignment")
155+
if not isinstance(key, str):
156+
raise ValueError("Metadata keys must be strings")
157+
md_value = Metadata(value)
158+
core.BNMetadataSetValueForKey(self.handle, key, md_value.handle)
159+
149160
def __str__(self):
150161
if self.is_string:
151162
return str(core.BNMetadataGetString(self.handle))
@@ -264,6 +275,13 @@ def is_array(self):
264275
def is_dict(self):
265276
return core.BNMetadataIsKeyValueStore(self.handle)
266277

278+
def append(self, value):
279+
"""Appends a value to the Metadata array."""
280+
if not self.is_array:
281+
raise TypeError("Metadata object is not an array and does not support append")
282+
md_value = Metadata(value) # Convert value to Metadata object
283+
core.BNMetadataArrayAppend(self.handle, md_value.handle)
284+
267285
def remove(self, key_or_index):
268286
if isinstance(key_or_index, str) and self.is_dict:
269287
core.BNMetadataRemoveKey(self.handle, key_or_index)

0 commit comments

Comments
 (0)