Python operation yaml instructions

1. Install PyYAML

pip install PyYAML

2. Load yaml file

Use the yaml.load() function directly

demo.yml :

kind: Deployment
apiVersion: apps/v1
metadata:
 name: podinfo
 namespace: yaml-demo
spec:
 replicas:1
 selector:
 matchLabels:
 app: podinfo
 template:
 metadata:
 labels:
 app: podinfo
 spec:
 containers:- name: podinfod
 image: quay.io/stefanprodan/podinfo:0.3.0
 ports:- containerPort:9898

load.py :

import yaml
import json

result = yaml.load(open('demo.yml'))
print json.dumps(result, indent=2)

Output:

{" kind":"Deployment","spec":{"replicas":1,"template":{"spec":{"containers":[{"image":"quay.io/stefanprodan/podinfo:0.3.0","name":"podinfod","ports":[{"containerPort":9898}]}]},"metadata":{"labels":{"app":"podinfo"}}},"selector":{"matchLabels":{"app":"podinfo"}}},"apiVersion":"apps/v1","metadata":{"namespace":"yaml-demo","name":"podinfo"}}

3. Persist dict to yml file

Use yaml.safe_dump() function

dump.py :

import yaml

d ={"kind":"Deployment","spec":{"replicas":1,"template":{"spec":{"containers":[{"image":"quay.io/stefanprodan/podinfo:0.3.0","name":"podinfod","ports":[{"containerPort":9898}]}]},"metadata":{"labels":{"app":"podinfo"}}},"selector":{"matchLabels":{"app":"podinfo"}}},"apiVersion":"apps/v1","metadata":{"namespace":"yaml-demo","name":"podinfo"}}
result = yaml.safe_dump(d, encoding='utf-8', allow_unicode=True, default_flow_style=False)open('demo.yml','w').write(result)

demo.yml :

apiVersion: apps/v1
kind: Deployment
metadata:
 name: podinfo
 namespace: yaml-demo
spec:
 replicas:1
 selector:
 matchLabels:
 app: podinfo
 template:
 metadata:
 labels:
 app: podinfo
 spec:
 containers:- image: quay.io/stefanprodan/podinfo:0.3.0
 name: podinfod
 ports:- containerPort:9898

Supplementary knowledge: Detailed explanation of Python's PyYAML module

Introduction

Python's PyYAML module is Python's YAML parser and generator.

installation

Simple installation

pip install pyyaml

Install from source

Download the source package PyYAML-3.13.tar.gz and decompress it, switch to the decompressed package directory under the command line and execute the following command:

python setup.py install

If you want to use LibYAML binding faster than the pure Python version, you need to download and install LibYAML first, and then execute the following command when installing PyYAML:

python setup.py –with-libyaml install

In order to use LibYAML-based parsers and generators, please use the CParser and CEmitter classes. E.g:

from yaml import load, dump
try:from yaml import Cloader as Loader, CDumper as Dumper
except ImportError:from yaml import Loader, Dumper

# ...

data =load(stream, Loader=Loader)

# ...

output =dump(data, Dumper=Dumper)

Note that there are some subtle but not really important differences between pure Python and LibYAML-based YAML parsers and generators.

Most frequently asked questions

Why does the YAML document shown below be serialized after deserialization, and the format of the resulting YAML document is different from the original one?

import yaml
document ="""
a:1
b:
 c:3
 d:4"""
print(yaml.dump(yaml.load(document)))

Among them, the output of the above code is:

a: 1
b: {c: 3, d: 4}

Regarding this issue, in fact, although the style of the final YAML document is inconsistent with the style of the original document, it is the correct result.

Because PyYAML by default will determine which format to use to represent a collection based on whether there are nested collections in a collection. If a collection is nested with other collections, it will be represented by the block style, otherwise it will be represented by the flow style.

If you want the collection to always be represented in a block style, you can set the default_flow_style parameter value of the dump() method to False, as shown below:

print(yaml.dump(yaml.load(document), default_flow_style=False))

The output of the above code is:

a: 1
b:
c: 3
d: 4

Detailed usage

Import the yaml module first:

import yaml

Load YAML

Warning: Calling yaml.load to process data received from untrusted sources may be risky. yaml.load is as powerful as pickle.load and can call all Python functions.

The yaml.load function is used to convert YAML documents into Python objects. As follows:

 yaml.load("""
...- Hesperiidae
...- Papilionidae
...- Apatelodidae
...- Epiplemidae
...""")[' Hesperiidae','Papilionidae','Apatelodidae','Epiplemidae']

The yaml.load function can accept a byte string representing a YAML document, a Unicode string, an opened binary file object, or an opened text file object as a parameter. If the parameters are byte strings or files, they must use utf-8, utf-16 or utf-16-le encoding. yaml.load will check the BOM (byte order mark) of byte strings or file objects and determine their encoding format accordingly. If no BOM is found, it will be assumed that they use utf-8 format encoding.

The return value of the yaml.load method is a Python object, as shown below:

 yaml.load("'hello': ''"){'hello':'\uf8ff'}withopen('document.yaml','w')as f:...   f.writelines('- Python\n- Ruby\n- Java')... 
 stream =open('document.yaml')
 yaml.load(stream)['Python','Ruby','Java']

If the string or file contains multiple YAML documents, you can use the yaml.load_all function to deserialize them all, and the result is a generator object that contains all the deserialized YAML documents:

 documents ="""
... name: bob
... age:18...---... name: alex
... age:20...---... name: jason
... age:16..."""
 datas = yaml.load_all(documents)
 datas
< generator object load_all at 0x105682228for data in datas:...print(data)...{'name':'bob','age':18}{'name':'alex','age':20}{'name':'jason','age':16}

PyYAML allows users to construct any type of Python object, as follows:

 document ="""
... none:[~,null]... bool:[true,false, on, off]... int:55... float:3.1415926... list:[Red, Blue, Green, Black]... dict:{name: bob, age:18}..."""
 yaml.load(document){'none':[None, None],'bool':[True, False, True, False],'int':55,'float':3.1415926,'list':['Red','Blue','Green','Black'],'dict':{'name':'bob','age':18}}

Even instances of Python classes can be constructed using the tag !!python/object, as shown below:

classPerson:...   def __init__(self, name, age, gender):...     self.name = name
...  self.age = age
...  self.gender = gender
... def __repr__(self):...return f"{self.__class__.__name__}(name={self.name!r}, age={self.age!r}, gender={self.gender!r})"... 
 yaml.load("""
...!! python/object:__main__.Person
... name: Bob
... age:18... gender: Male
...""") Person(name='Bob', age=18, gender='Male')

Note that if you receive a YAML document from an untrusted source (such as the Internet) and construct an arbitrary Python object from it, there may be certain risks. Using the yaml.safe_load method can limit this behavior to only constructing simple Python objects, such as integers or lists.

Define a subclass that inherits from the yaml.YAMLObject class, and then set the value of the class attribute yaml_loader of this subclass to yaml.SafeLoader, so that objects of this class are marked as safe and can be used by the yaml.safe_load method Recognition. However, one thing to note is that when deserializing such Python objects, you can only use the safe_load and safe_load_all methods.

Dump YAML

The yaml.dump function accepts a Python object and generates a YAML document.

import yaml
 emp_info ={'name':'Lex',...'department':'SQA',...'salary':8000,...'annual leave entitlement':[5,10]...}print(yaml.dump(emp_info))
annual leave entitlement:[5,10]
department: SQA
name: Lex
salary:8000

yaml.dump can accept a second optional parameter, which is used to write the generated YAML text. The value of this parameter can be an open text or binary file object. If this optional parameter is not provided, the generated YAML document is returned directly.

withopen('document.yaml','w')as f:...   yaml.dump(emp_info, f)...import os
 os.system('cat document.yaml')
annual leave entitlement:[5,10]
department: SQA
name: Lex
salary:80000

If you want to serialize multiple Python objects into a YAML stream, you can use the yaml.dump_all function. This function accepts a Python list or generator object as the first parameter, representing multiple Python objects to be serialized.

 obj =[{'name':'bob','age':19},{'name':20,'age':23},{'name':'leo','age':25}]print(yaml.dump_all(obj)){age:19, name: bob}---{age:23, name:20}---{age:25, name: leo}

You can even serialize an instance of a Python class as follows:

classPerson:...   def __init__(self, name, age, gender):...     self.name = name
...  self.age = age
...  self.gender = gender
... def __repr__(self):...return f"{self.__class__.__name__}(name={self.name!r}, age={self.age!r}, gender={self.gender!r})"...print(yaml.dump(Person('Lucy',26,'Female')))!!python/object:__main__.Person {age:26, gender: Female, name: Lucy}

The yaml.dump and yaml.dump_all methods also support multiple keyword parameters to specify the style of the YAML document in the generated YAML stream and whether it contains other information. Let's introduce the meaning and usage of each parameter in detail below.

stream

Specify the file object to be opened due to output YAML stream. The default value is None, which means to return as the return value of the function.

default_flow_style

Whether to display sequence and mapping in flow style by default. The default value is None, which means that the flow style is used for YAML flows that do not contain nested collections. When set to True, sequence and map use block style.

default_style

The default value is None. Indicates that the scalar is not wrapped in quotes. When set to'”', it means that all scalars are wrapped in double quotes. When set to “'”, it means that all scalars are wrapped in single quotes.

canonical

Whether to display YAML documents in canonical form. The default value is None, which means formatting with the value set by other keyword parameters instead of using the canonical form. When set to True, the content in the YAML document will be displayed in a canonical form.

indent

Indicates the indentation level. The default value is None, which means to use the default indentation level (two spaces), which can be set to other integers.

width

Indicates the maximum width of each line. The default value is None, which means the default width of 80 is used.

allow_unicode

Whether to allow unicode characters in the YAML stream. The default value is False, which will escape unicode characters. When set to True, unicode characters will be displayed normally in the YAML document and will not be escaped.

line_break

Set the line break. The default value is None, which means the newline character is ", which is empty. It can be set to \n, \r or \r\n.

encoding

Encode the YAML stream using the specified encoding and output as a byte string. The default value is None, which means that no encoding is performed and the output is a general string.

explicit_start

Does each YAML document contain explicit end-of-command tags? The default value is None, which means that when there is only one YAML document in the stream, no explicit end-of-command tag is included. When set to True, all YAML documents in the YAML stream contain an explicit end-of-command tag.

explicit_end

Whether each YAML document contains an explicit end-of-document tag. The default value is None, which means that the YAML document in the stream does not contain an explicit end-of-document tag. When set to True, all YAML documents in the YAML stream contain an explicit end-of-document tag.

version

Used to specify the version number of YAML in the YAML document, the default value is None, which means that the version number is not specified in the YAML. It can be set to a tuple or list containing two elements, but the first element must be 1, otherwise an exception will be raised. The currently available YAML version numbers are 1.0, 1.1, and 1.2.

tags

Used to specify the tags to be included in the YAML document. The default value is None, which means no label instruction is specified. It can be set as a dictionary containing tags. The key-value pairs in the dictionary correspond to different tag names and values.

 data ={'code':200,'status':'success','message':[10, True,"Got it"]}print(yaml.dump(data, version=(1,2))) #Set YAML version
%YAML 1.2---
code:200
message:[10,true, Got it]
status: success

 print(yaml.dump(data, version=(1,2), tags={'!name!':'test'})) #Set label instructions
%YAML 1.2%TAG !name! test
---
code:200
message:[10,true, Got it]
status: success

 print(yaml.dump(data, #Set to use block style
...   version=(1,2),...         tags={'!name!':'test'},...         default_flow_style=False))%YAML 1.2%TAG !name! test
---
code:200
message:-10-true- Got it
status: success

 print(yaml.dump(data, #Set the scalar to use single quotes
...   version=(1,2),...         tags={'!name!':'test'},...         default_flow_style=False,...         default_style="'"))%YAML 1.2%TAG !name! test
- - - ' code':!!int '200''message':-!!int '10'-!!bool 'true'-'Got it''status':'success'print(yaml.dump(data, #Set the scalar to use double quotes
...   version=(1,2),...         tags={'!name!':'test'},...         default_flow_style=False,...         default_style='"'))%YAML 1.2%TAG !name! test
- - - " code":!!int "200""message":-!!int "10"-!!bool "true"-"Got it""status":"success"print(yaml.dump(data, #Set the YAML document to include explicit instruction end tags and document end tags
...   explicit_start=True,...         explicit_end=True))---
code:200
message:[10,true, Got it]
status: success
... print(yaml.dump(data, canonical=True)) #Set document usage specification form
- - - !! map {?!!str "code":!!int "200",?!!str "message":!!seq [!!int "10",!!bool "true",!!str "Got it",],?!!str "status":!!str "success",}print(yaml.dump(data, encoding='utf-8')) #Use utf for YAML stream-8 format for encoding
b'code: 200\nmessage: [10, true, Got it]\nstatus: success\n'
 user_info ={'name':'Jacky Cheung','age':57,'nickname':['Song god','Ufly']}print(yaml.dump(user_info)) #If you do not set allow_unicode parameters, unicode characters will be escaped
age:57
name:"\u5F20\u5B66\u53CB""\u5916\u53F7":["\u6B4C\u795E","\u4E4C\u8747\u54E5"]print(yaml.dump(user_info, allow_unicode=True)) #Set to allow unicode characters
age:57
name:Jacky Cheung
nickname:[Song god,Ufly]

Construction, representation and analysis

You can define your own application-specific tags. The easiest way is to define a subclass of yaml.YAMLObject as follows:

classPerson(yaml.YAMLObject):...   yaml_tag ='!Person'...   def __init__(self, name, age, gender):...     self.name = name
...  self.age = age
...  self.gender = gender
... def __repr__(self):...return f"{self.__class__.__name__}(name={self.name!r}, age={self.age!r}, gender={self.gender!r})"...

The above definition is sufficient to automate the deserialization and serialization of Person objects:

 text ="""
...- - - ! Person
... name: Bob
... age:22... gender: Male
..."""
 yaml.load(text)Person(name='Bob', age=22, gender='Male')print(yaml.dump(Person('Bob',22,'Male')))!Person {age:22, gender: Male, name: Bob}

yaml.YAMLObject uses metaclass magic to register a constructor used to convert YAML nodes into class instances and a presenter used to deserialize YAML nodes into Python class instances.

If you don't want to use metaclasses, you can use yaml.add_constructor and yaml.add_representer to register your constructors and representers. As follows:

classDice(tuple):...   def __new__(cls, a, b):...return tuple.__new__(cls,[a, b])...   def __repr__(self):...return'Dice(%s, %s)'% self
... print(Dice(3,6))Dice(3,6)

The representation of the default Dice object does not look pretty:

print(yaml.dump(Dice(3,6)))!!python/object/new:__main__.Dice
- !! python/tuple [3,6]

Suppose you want a Dice object to be serialized and expressed as AdB, for example:

print(yaml.dump(Dict(3, 6))) # Expected output: 3d6

First, you need to define a *representers used to convert Dict objects into scalar nodes marked with the !dict tag, and then register it, as shown below:

 def dice_representer(dumper, data):...return dumper.represent_scalar('!dice','%sd%s'% data)... 
 yaml.add_representer(Dice, dice_representer)

Now, the input after serializing an instance of the Dice object is as expected:

 yaml.add_representer(Dice, dice_representer)print(yaml.dump({'gold':Dice(10,6)})){gold:!dice '10d6'}

Next, let's implement a constructor that converts the scalar node marked with the !dice tag into a Dice object and register it:

 def dice_constructor(loader, node):...   value = loader.construct_scalar(node)...   a, b =map(int, value.split('d'))...returnDice(a, b)... 
 yaml.add_constructor('!dice', dice_constructor)

Then, you can load a Dice object:

 text ='initial hit points: !dice 8d4'print(yaml.load(text)){'initial hit points':Dice(8,4)}

If you don't want to specify the !dice label anywhere, you can use the add_implicit_resolver function to tell PyYAML that all unlabeled ordinary scalars like XdY have an explicit label !dice, as shown below:

import re
 pattern = re.compile(r'^\d+d\d+$')
 yaml.add_implicit_resolver('!dice', pattern)

Now, it is not necessary to use tags when defining Dice objects, as shown below:

print(yaml.dump({'treasure':Dice(10,20)})){treasure: 10d20}print(yaml.load('damage: 5d10')){'damage':Dice(5,10)}

When marking an object as safe, you can only use the safe_load or safe_load_all method when deserializing such an object, otherwise an error will be reported, as shown below:

classPerson(yaml.YAMLObject):...   yaml_tag ='!Person'...   yaml_loader = yaml.SafeLoader
... def __init(self, name, age, gender):...     self.name = name
...  self.age = age
...  self.gender = gender
... def __repr__(self):...return f"Person(name={self.name!r}, age={self.age!r}, gender={self.gender!r})"... 
 text ="""
...! Person
... name: Bob
... age:22... gender: Male
..."""
 yaml.load(text) #Do not use safe_load or safe_load_all method will report an error
Traceback(most recent call last):...
yaml.constructor.ConstructorError: could not determine a constructor for the tag '!Person'in"<unicode string ", line 2, column 1:!Person
  ^
 yaml.safe_load(text) #Use safe_The load method can be deserialized normally
Person(name='Bob', age=22, gender='Male')

YAML syntax

This part will introduce the most common YAML structures and corresponding Python objects.

Documentation

A YAML stream is a collection of zero or more YAML documents. The empty YAML stream does not contain YAML documents. YAML documents are separated by document start tag —. YAML documents can contain an optional end-of-document tag.... If there is only one document in the stream, the document start tag may not be used. A document that contains a document start tag can be called an explicit document, and a document that does not contain a document start tag can be called an implicit document.

Here is an implicit document:

– Multimedia
– Internet
– Education

Here is an explicit document:


– Afterstep
– CTWM
– Oroborus

Here is a YAML stream containing multiple documents:


– Employee
– Manager
– CEO
– CTO

– Student

– C
– C# # YAML uses'#' to indicate comments (a space before'#')
– C++
– Cold Fusion

Block sequence

In the block content, use a dash (dash)-followed by a space (Space) to indicate items in the sequence.

Here is a document containing a sequence of blocks:

– id
– name
– age

The above document represents a Python object as follows:

[ ‘id’, ‘name’, ‘age’]

Block sequences can be nested:


– Python
– Ruby
– JavaScript
– PHP

– Unix
– Linux
– Windows

The above document represents the following Python objects:

[[ ‘Python’, ‘Ruby’, ‘JavaScript’, ‘PHP’], [‘Unix’, ‘Linux’, ‘Windows’]]

In the nested block sequence, the inner sequence can start directly from the current line without having to start from a new line, as shown below:

– – Python
– Ruby
– JavaScript
– PHP
– – Unix
– Linux
– Windows

The block sequence can be nested in the block map. In this case, the block sequence does not need to be indented, as shown below:

Programing Languages:
– Java
– Swift
– C++
– Go
Operation System:
– Unix
– Linux
– Windows
– OSX

The above document represents the following Python objects:

{' Programing Languages':['Java','Swift','C++','Go'],'Operation System':['Unix','Linux','Windows']}

Block mapping

In the block content, use a colon: followed by a space to separate the keys and values in the map.

name: bob
age:28
gender: Male

The above document represents the following Python objects:

{ ‘name’: ‘bob’, ‘age’: 28, ‘gender’: ‘Male’}

Complex keys are represented by a question mark? followed by a space, as shown below:

?!! python/tuple [0,0]: Start
?!! python/tuple [3,5]: End

The above document represents the following Python objects:

{(0, 0): ‘Start’, (3, 5): ‘End’}

Block mapping can be nested, as shown below:

Employee:
 Job_title: Employee
 Salary:5000
 Annual Leave:10
Manager:
 Job_title: Manager
 Salary:8000
 Annual Leave:15

The above document represents the following Python objects:

{ ‘Employee’: {‘Job_title’: ‘Employee’, ‘Salary’: 5000, ‘Annual Leave’: 10},
‘Manager’: {‘ Job_title’: ‘Manager’, ‘Salary’: 8000, ‘Annual Leave’: 15}}

The block map can be nested in the block sequence as follows:

– name: PyYAML
status: 4
license: MIT
language: Python
– name: PySyck
status: 5
license: BSD
language: Python

The above document represents the following Python objects:

[{ ‘name’: ‘PyYAML’, ‘status’: 4, ‘license’: ‘MIT’, ‘language’: ‘Python’},
{ ‘name’: ‘PySyck’, ‘status’: 5, ‘license’: ‘BSD’, ‘language’: ‘Python’}]

Flow collection

The syntax of stream collections in YAML is very similar to the syntax of list and dictionary structures in Python, as shown below:

{ str: [15, 17], con: [16, 16], dex: [17, 18], wis: [16, 16], int: [10, 13], chr: [5, 8] }

The above document represents the following Python objects:

{ ‘dex’: [17, 18], ‘int’: [10, 13], ‘chr’: [5, 8], ‘wis’: [16, 16], ‘str’: [15, 17], ‘con’: [16, 16]}

Scalar

There are 5 styles for scalar in YAML, among which there are two styles for block scalar:

Literal style

Folded style

There are three styles of flow scalar:

Plain style

Single-quoted style

Double-quoted style

Examples of these five styles are as follows:

plain: Hello World
single-quoted:'All content will be output as is'
double-quoted: "Need to use a backslash to transfer special characters"
literal: |
Every row
Metropolis
Contains newlines
Every blank line in the middle
Will use newline instead
folded:
Except the last line
Newline
Will keep
Newline at the end of other lines
Will use a space instead
Blank line in the middle
Will use a newline character instead

The above document represents the following Python objects:

{ ‘plain’: ‘Hello World’,
'single-quoted':'All content will be output as is',
'double-quoted':'Special characters need to be transferred with a backslash',
'literal':'Every line\n will contain a newline character\nEvery blank line in the middle\n\nwill be replaced by a newline character\n',
'folded':'Except for the newline character of the last line, the newline character at the end of the other lines will be replaced by a space instead of the blank line in the middle\n will use a newline character instead of\n'}

Each style has its own characteristics. Ordinary scalar does not use indicators to indicate its start and end, so it is the most restricted style. Ordinary scalars are naturally suitable for the names of parameters and attributes

Using single-quoted scalars, you can represent any value that does not contain special characters. There is no escape for single-quoted scalars, unless it is a pair of adjacent quotation marks "replaced by single quotation marks".

Double quotes are the most powerful style and the only style that can represent any scalar value. Characters within double-quoted scalars are allowed to be escaped. Use escape sequences \x* and \u*** to express any ASCII or Unicode character.

There are two block scalar styles: text style and folding style. The text style is the most suitable style for large text blocks (such as source code). The folding style is similar to the text style, but the newline character between two adjacent non-blank lines will be replaced with a space to become a line.

Alias

Use YAML to represent any object of class diagram structure. If you want to refer to the same object from different parts of the document, you need to use anchors and aliases.

Among them, anchor is represented by & and alias is represented by *. The following example will demonstrate the use of anchors and aliases:

emp1:&A
 name: bob
 age:28
 gender: Male
emp2:*A

The above document represents the following Python objects:

{ ’emp1′: {‘name’: ‘bob’, ‘age’: 28, ‘gender’: ‘Male’},
’emp2′: {‘name’: ‘bob’, ‘age’: 28, ‘gender’: ‘Male’}}

PyYAML now supports recursive objects. The following document represents a Python list whose elements are the list itself.

&A [ *A ]

label

The label is used to identify the data type of the node. The definition of standard YAML tags can refer to this document:

http://yaml.org/type/index.html

The label can be implicitly as follows:

boolen:true
integer:3
float:3.14

The above document represents the following Python objects:

{ ‘boolean’: True, ‘integer’: 3, ‘float’: 3.14}

Labels can also be explicit, as shown below:

boolean:!!bool "true"
integer:!!int "3"
float:!!float "3.14"

The above document represents the following Python objects:

{ ‘boolean’: True, ‘integer’: 3, ‘float’: 3.14}

Ordinary scalars without explicitly defined labels are subject to implicit label resolution. Implicit label resolution checks the scalar value based on a set of regular expressions, and if one of them matches, assigns the corresponding tag to the scalar. PyYAML allows applications to add custom implicit tag parsers.

YAML tags and Python3 objects

YAML tag Python object
Standard YAML tags
!! null None
!! bool bool
!! int int
!! float float
!! binary bytes
!! timestamp datetime.datetime
!! omap, !!pairs The elements are a list of two tuples
!! set set
!! str str
!! seq list
!! map dict
Python special tags
!! python/none None
!! python/bool bool
!! python/bytes bytes
!! python/str str
!! python/unicode str
!! python/int int
!! python/long int
!! python/float float
!! python/complex complex
!! python/list list
!! python/tuple tuple
!! python/dict dict
Complex Python tags
!! python/name:module.name module.name
!! python/module:package.module package.module
!! python/object:module.cls Instance of module.cls
!! python/object/new:module.cls Instance of module.cls
!! python/object/apply:module.func Return value of method func(...)

String conversion

In Python3, objects of type str will be transformed into scalars identified by the label !!str; objects of type bytes will be transformed into scalars identified by the label !!binary. In order to consider compatibility, the tags !!python/str and !!python/unicode can still be used, and the scalar identified by them will be converted into objects of type str.

Name and module

To represent static Python objects, such as functions and classes, you can use the complex label Python !!python/name. The following example demonstrates how to represent the dump method in the yaml module:

!! python/name:yaml.dump

Similarly, modules can use tags!!python/module:

!! python/module.yaml

Object

Any pickleable object can be serialized using the tag!!python/object:

!! python/object:module.Class { attribute: value, … }

In order to support the pickle protocol, PyYAML provides two additional tags

!! python/object/new:module.Class and !!python/object/apply:module.function

The usage of these two labels is as follows:

!! python/object/new:module.Class
args:[argument,...]
kwds:{key: value,...}
stat:...
listitems:[item,...]
dictitems:[key: value,...]!!python/object/apply:module.function
args:[argument,...]
kwds:{key: value,...}
state:...
listitems:[item,...]
dictitems:[key: value,...]

The above description of python operation yaml is all the content shared by the editor, I hope to give you a reference.

Recommended Posts

Python operation yaml instructions
Python file operation
python operation kafka
Python operation SQLite database
Python automated operation and maintenance 2
Python negative modulus operation example
Python automated operation and maintenance 1
Quick start Python file operation
Use nohup command instructions in python
Python preliminary implementation of word2vec operation
Python list comprehension operation example summary
Python file operation basic process analysis
Implementation of python selenium operation cookie
Some examples of python operation redis
Example operation of python access Alipay
The operation of python access hdfs
Python handles operation code to execl
Instructions for using python asynchronous async library
Python file and directory operation code summary
Python implements image outer boundary tracking operation