pylibfdt: Support copy.copy() and copy.deepcopy() on Property

`libfdt.Property` subclasses `bytearray` and has a two-argument
`__init__(self, name, value)` constructor. Because `bytearray`'s default
copy/reduce protocol passes only the raw byte buffer to the constructor
(and does not copy instance attributes), calling `copy.copy()` or
`copy.deepcopy()` on a `Property` fails with `TypeError:
Property.__init__() missing 1 required positional argument: 'value'`.

Implement `__copy__()` and `__deepcopy__()` on `Property` so shallow and
deep copies preserve both `name` and the byte contents, and add a unit
test in `tests/pylibfdt_tests.py`.

Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-7-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
main
Douglas Anderson 2026-11-01 14:01:13 -08:00 committed by David Gibson
parent 99c16cb0d7
commit 4e9e220985
2 changed files with 12 additions and 0 deletions

View File

@ -908,6 +908,12 @@ class Property(bytearray):
bytearray.__init__(self, value)
self.name = name

def __copy__(self):
return type(self)(self.name, self)

def __deepcopy__(self, memo):
return type(self)(self.name, self)

def as_cell(self, fmt):
return struct.unpack('>' + fmt, self)[0]


View File

@ -4,6 +4,7 @@
# Written by Simon Glass <sjg@chromium.org>
#

import copy
import struct
import sys
import types
@ -192,6 +193,11 @@ class PyLibfdtBasicTests(unittest.TestCase):
prop = self.fdt.get_property_by_offset(poffset)
self.assertEqual(prop.name, 'compatible')
self.assertEqual(prop, b'test_tree1\0')
for copied in (copy.copy(prop), copy.deepcopy(prop)):
self.assertIsInstance(copied, libfdt.Property)
self.assertIsNot(copied, prop)
self.assertEqual(copied.name, 'compatible')
self.assertEqual(copied, b'test_tree1\0')

with self.assertRaises(FdtException) as e:
self.fdt.get_property_by_offset(-2)