FrozenSoul90
FrozenSoul90

Reputation: 313

How to add custom nested tags in PyYaml?

I want to be able to use nested tags

I got the custom tags working separately using the below code, but unable to use both in same value

SafeLoader.add_constructor("!include", include)
SafeLoader.add_constructor("!path", gen_path)

This is how my sample yaml would look

key: !include !path special_file.yaml

Note:

!path => Generates a special path after some processing from mysql

!include => loads that yaml content of a file into the current reading data

Upvotes: 2

Views: 516

Answers (1)

Anthon
Anthon

Reputation: 76578

Yours are shorthand tags and if you look at the production rule for that in the YAML 1.1 specification, you'll see:

[112]   c-ns-shorthand-tag  ::=   ( c-primary-tag-handle ns-tag-char+ )
                                | ( ns-secondary-tag-handle ns-uri-char+ )
                                | ( c-named-tag-handle ns-uri-char+ )

That rule is only used in the tag property:

[110]   c-ns-tag-property   ::=   c-verbatim-tag | c-ns-shorthand-tag
                                | c-ns-non-specific-tag

And that is used in the node property:

[107]   c-ns-properties(n,c)    ::=   ( c-ns-tag-property
                                      ( s-separate(n,c) c-ns-anchor-property )? )
                                    | ( c-ns-anchor-property
                                      ( s-separate(n,c) c-ns-tag-property )? )

As you can see, none of these include repetition of the tag element itself, only for characters within a tag ( ns-tag-char+ ).

Therefore you cannot have multiple tags on a single node in YAML.

The YAML 1.1 spec that PyYAML partly implements, was replaced over ten years ago by YAML 1.2, but that has the same restriction, so it won't bring you anything to upgrade your YAML parser.

Upvotes: 3

Related Questions