11cimport cython
22
3+ from typing import Optional
4+
35@cython.final
46cdef class LexborAttributes:
57 """ A dict-like object that represents attributes."""
@@ -23,16 +25,32 @@ cdef class LexborAttributes:
2325 yield key.decode(_ENCODING)
2426 attr = attr.next
2527
26- def __setitem__ (self , str key , value ):
27- value = str ( value)
28+ def __setitem__ (self , str key , object value ):
29+ value = value
2830 bytes_key = key.encode(_ENCODING)
29- bytes_value = value.encode(_ENCODING)
30-
31- lxb_dom_element_set_attribute(
32- < lxb_dom_element_t * > self .node,
33- < lxb_char_t * > bytes_key, len (bytes_key),
34- < lxb_char_t * > bytes_value, len (bytes_value),
35- )
31+ bytes_value = value.encode(_ENCODING) if value else b" "
32+ cdef lxb_dom_attr_t * attr
33+ cdef lxb_dom_document_t * doc
34+
35+ if value is None :
36+ # N.B. This is suboptimal, but there is not API to set empty attributes
37+ attr = lxb_dom_element_set_attribute(
38+ < lxb_dom_element_t * > self .node,
39+ < lxb_char_t * > bytes_key, len (bytes_key),
40+ NULL , 0
41+ )
42+ doc = (< lxb_dom_node_t* > attr).owner_document
43+ lexbor_str_destroy(attr.value, doc.text, 0 )
44+ attr.value = NULL
45+
46+ elif isinstance (value, str ) or isinstance (value, unicode ) :
47+ lxb_dom_element_set_attribute(
48+ < lxb_dom_element_t * > self .node,
49+ < lxb_char_t * > bytes_key, len (bytes_key),
50+ < lxb_char_t * > bytes_value, len (bytes_value),
51+ )
52+ else :
53+ raise TypeError (" Expected str or unicode, got %s " % type (value))
3654
3755 def __delitem__ (self , key ):
3856 try :
0 commit comments