Skip to content

Commit 522b60c

Browse files
jeanseb6windrjarry
authored andcommitted
data: cast data value to proper type
This patch allows the function `cdata_leaf_value` to return a better casted type.
1 parent cf32d6e commit 522b60c

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

libyang/data.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -788,9 +788,9 @@ def _to_dict(node, parent_dic):
788788
elif node.schema.nodetype == SNode.LEAFLIST:
789789
if name not in parent_dic:
790790
parent_dic[name] = _init_yang_list(node.schema)
791-
parent_dic[name].append(DLeaf.cdata_leaf_value(node))
791+
parent_dic[name].append(DLeaf.cdata_leaf_value(node, self.context))
792792
elif node.schema.nodetype == SNode.LEAF:
793-
parent_dic[name] = DLeaf.cdata_leaf_value(node)
793+
parent_dic[name] = DLeaf.cdata_leaf_value(node, self.context)
794794

795795
dic = {}
796796
dnode = self
@@ -928,10 +928,10 @@ class DList(DContainer):
928928
@DNode.register(SNode.LEAF)
929929
class DLeaf(DNode):
930930
def value(self) -> Any:
931-
return DLeaf.cdata_leaf_value(self.cdata)
931+
return DLeaf.cdata_leaf_value(self.cdata, self.context)
932932

933933
@staticmethod
934-
def cdata_leaf_value(cdata) -> Any:
934+
def cdata_leaf_value(cdata, context: "libyang.Context" = None) -> Any:
935935

936936
val = lib.lyd_get_value(cdata)
937937
if val == ffi.NULL:
@@ -942,8 +942,9 @@ def cdata_leaf_value(cdata) -> Any:
942942
val_type = ffi.new("const struct lysc_type **", ffi.NULL)
943943

944944
# get real value type
945+
ctx = context.cdata if context else ffi.NULL
945946
ret = lib.lyd_value_validate(
946-
ffi.NULL,
947+
ctx,
947948
term_node.schema,
948949
str2c(val),
949950
len(val),
@@ -954,10 +955,18 @@ def cdata_leaf_value(cdata) -> Any:
954955

955956
if ret in (lib.LY_SUCCESS, lib.LY_EINCOMPLETE):
956957
val_type = val_type[0].basetype
957-
if val_type == Type.BOOL:
958-
return val == "true"
958+
if val_type in Type.STR_TYPES:
959+
return val
959960
if val_type in Type.NUM_TYPES:
960961
return int(val)
962+
if val_type == Type.BOOL:
963+
return val == "true"
964+
if val_type == Type.DEC64:
965+
return float(val)
966+
if val_type == Type.LEAFREF:
967+
return DLeaf.cdata_leaf_value(cdata.value.leafref, context)
968+
if val_type == Type.EMPTY:
969+
return None
961970
return val
962971

963972
raise TypeError("value type validation error")

0 commit comments

Comments
 (0)