feat: speed up creating Variant objects (#144)

This commit is contained in:
J. Nick Koston 2022-11-03 22:56:18 +01:00 committed by GitHub
parent aa87b82856
commit 2ff84e3ac5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 15 deletions

View File

@ -19,5 +19,5 @@ cdef class SignatureTree:
cdef class Variant:
cdef public object type
cdef public str signature
cdef public object signature
cdef public object value

View File

@ -405,31 +405,27 @@ class Variant:
"""Init a new Variant."""
if type(signature) is SignatureTree:
signature_tree = signature
self.signature = signature_tree.signature
self.type = signature_tree.types[0]
elif type(signature) is SignatureType:
signature_type = signature
signature_str = signature.signature
signature_tree = None
self.signature = signature.signature
self.type = signature
elif type(signature) is str:
signature_tree = get_signature_tree(signature)
self.signature = signature
self.type = signature_tree.types[0]
else:
raise TypeError(
"signature must be a SignatureTree, SignatureType, or a string"
)
if signature_tree:
if verify and len(signature_tree.types) != 1:
self.value = value
if verify:
if signature_tree and len(signature_tree.types) != 1:
raise ValueError(
"variants must have a signature for a single complete type"
)
signature_str = signature_tree.signature
signature_type = signature_tree.types[0]
if verify:
signature_type.verify(value)
self.type = signature_type
self.signature = signature_str
self.value = value
self.type.verify(value)
def __eq__(self, other: Any) -> bool:
if type(other) is Variant:

View File

@ -220,3 +220,14 @@ def test_invalid_variants():
with pytest.raises(SignatureBodyMismatchError):
tree.verify([con])
def test_variant_signature_type():
tree = SignatureTree("as")
var = Variant(tree.types[0], ["foo", "bar"])
assert var.type == tree.types[0]
assert var.value == ["foo", "bar"]
assert var.signature == "as"
with pytest.raises(SignatureBodyMismatchError):
Variant(tree.types[0], "wrong")