I have googled without success so I would like what does isinstance
means combined with yaml ScalarNode, SequenceNode and MappingNode? (I know already what isinstance
is)
For example
if isinstance(v,yaml.ScalarNode):
#do something
elif isinstance(v,yaml.SequenceNode):
#something else
elif isinstance(v, yaml.MappingNode):
#another thing
Node types are a part of YAML's Representation data structure. YAML defines its (de)serialization pipeline as follows:
The Representation is a, potentially cyclic, graph of nodes. In it, anchors and aliases have been resolved. In PyYAML, you typically use subgraphs of this data structure to implement custom constructors and representers that generate your native objects, as indicated by the arrows in the diagram.
A ScalarNode is a node representing a single scalar in the YAML source or output. A single scalar can be a plain scalar (eg foo
), a quoted scalar ( 'foo'
or "foo"
), or a block scalar (starting with |
or >
). The scalar content, with escape sequences, newlines, indentation already processed, is available in the field .value
as string. This is even true for values that are by default constructed into non-strings. For example, true
will by default generate a boolean value, but as ScalarNode, it contains the value "true"
as string.
SequenceNode is a node representing a sequence. The value
field of a SequenceNode
contains a list of nodes that correspond to the items in the sequence.
MappingNode is a node representing a mapping. The value
field of a MappingNode
contains a list of tuples, where each tuple consists of the key node and the value node.
All nodes have a field tag
that contains the resolved tag of the node. ie a ScalarNode
with value true
would typically have the tag yaml.org,2002:bool
. The resolved tag depends on the loader you use, for example if you use PyYAML's BaseLoader
, true
will resolve to a normal string, which is yaml.org,2002:str
. In any case, if there was an explicit tag on the node (eg !!str
, that tag will be in the tag
field.
Coming back to the question, this kind of code is typically used in custom constructors. They get a node as input and are to produce a native value and return it. Usually, a custom constructor expects a specific kind of node but if you want to do proper error reporting, you still want to check whether you actually got the kind of node you need. For this, you use the code you posted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.