diff --git a/01. Python/05. Modules/01.3 Serialization (yaml).ipynb b/01. Python/05. Modules/01.3 Serialization (yaml).ipynb index 53617ac..ede849c 100755 --- a/01. Python/05. Modules/01.3 Serialization (yaml).ipynb +++ b/01. Python/05. Modules/01.3 Serialization (yaml).ipynb @@ -1 +1,1312 @@ -{"cells": [{"cell_type": "markdown", "metadata": {}, "source": [""]}, {"cell_type": "markdown", "id": "floating-values", "metadata": {}, "source": ["# YAML \n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Table of Contents \n* [YAML Tutorial Quick Start: A Simple File](#yaml_tutorial_quick_start:_a_simple_file)\n* [Installation](#installation)\n* [Read YAML](#read_yaml)\n* [Introduction](#introduction)\n * [Rules for Creating YAML file](#rules_for_creating_yaml_file)\n * [Indentation of YAML](#indentation_of_yaml)\n * [Basics Components](#basics_components)\n * [Conventional Block Format](#conventional_block_format)\n * [Inline Format](#inline_format)\n * [Folded Text](#folded_text)\n* [YAML Syntax and format](#yaml_syntax_and_format)\n * [String](#string)\n * [Short texts](#short_texts)\n * [Long text](#long_text)\n * [Numbers](#numbers)\n * [Boolean](#boolean)\n * [Collections and Structures](#collections_and_structures)\n * [Lists](#lists)\n * [Maps](#maps)\n * [References](#references)\n * [Multiple documents](#multiple_documents)\n * [Tags](#tags)\n\n---"]}, {"cell_type": "markdown", "id": "contained-running", "metadata": {}, "source": ["**Y**AML **A**in't **M**arkup **L**anguage (**YAML**) is a serialization language that has steadily increased in popularity over the last few years. It's often used as a format for configuration files, but its object serialization abilities make it a viable replacement for languages like JSON. This YAML tutorial will demonstrate the language syntax with a guide and some simple coding examples in Python. YAML has broad language support and maps easily into native data structures. It's also easy to for humans to read, which is why it's a good choice for configuration. The YAML acronym was shorthand for **Yet Another Markup Language**. But the maintainers renamed it to **YAML Ain't Markup Language** to place more emphasis on its data-oriented features."]}, {"cell_type": "markdown", "id": "reasonable-proportion", "metadata": {}, "source": ["YAML is a recently introduced data serialization format and is very comfortable for human reading and writing. **YAML is poised to replace XML and JSON**."]}, {"cell_type": "markdown", "id": "apparent-makeup", "metadata": {}, "source": ["", "\n", "## YAML Tutorial Quick Start: A Simple File"]}, {"cell_type": "markdown", "id": "intense-visitor", "metadata": {}, "source": ["Let's take a look at a YAML file for a brief overview."]}, {"cell_type": "markdown", "id": "tropical-chicken", "metadata": {}, "source": ["```yaml\n", "---\n", "quiz: \n", " description: >\n", " \"This Quiz is to learn YAML.\"\n", " questions:\n", " - [\"How many planets are there in the solar system?\", \"Name the non-planet\"]\n", " - \"Who is found more on the web?\"\n", " - \"What is the value of pi?\"\n", " - \"Is pluto related to platonic relationships?\"\n", " - \"How many maximum members can play TT?\"\n", " - \"Which value is no value?\"\n", " - \"Don't you know that the Universe is ever-expanding?\"\n", " \n", " answers:\n", " - [8, \"pluto\"]\n", " - cats\n", " - 3.141592653589793\n", " - true\n", " - 4\n", " - null\n", " - no\n", "# explicit data conversion and reusing data blocks\n", "extra:\n", " refer: &id011 # give a reference to data\n", " x: !!float 5 # explicit conversion to data type float\n", " y: 8\n", " num1: !!int \"123\" # conversion to integer\n", " str1: !!str 120 # conversion to string\n", " again: *id011 # call data by giving the reference\n", "```"]}, {"cell_type": "markdown", "id": "cooperative-johns", "metadata": {}, "source": ["The identical `json` file is:"]}, {"cell_type": "markdown", "id": "expanded-amino", "metadata": {}, "source": ["```json\n", "{\n", " \"quiz\": {\n", " \"description\": \"\\\"This Quiz is to learn YAML.\\\"\\n\",\n", " \"questions\": [\n", " [\n", " \"How many planets are there in the solar system?\",\n", " \"Name the non-planet\"\n", " ],\n", " \"Who is found more on the web?\",\n", " \"What is the value of pi?\",\n", " \"Is pluto related to platonic relationships?\",\n", " \"How many maximum members can play TT?\",\n", " \"Which value is no value?\",\n", " \"Don't you know that the Universe is ever-expanding?\"\n", " ],\n", " \"answers\": [\n", " [\n", " 8,\n", " \"pluto\"\n", " ],\n", " \"cats\",\n", " 3.141592653589793,\n", " true,\n", " 4,\n", " null,\n", " false\n", " ]\n", " },\n", " \"extra\": {\n", " \"refer\": {\n", " \"x\": 5.0,\n", " \"y\": 8\n", " },\n", " \"num1\": 123,\n", " \"str1\": \"120\",\n", " \"again\": {\n", " \"x\": 5.0,\n", " \"y\": 8\n", " }\n", " }\n", "}\n", "```"]}, {"cell_type": "markdown", "id": "alpine-center", "metadata": {}, "source": ["JSON and YAML have similar capabilities, and you can convert most documents between the formats."]}, {"cell_type": "markdown", "id": "equipped-police", "metadata": {}, "source": ["", "\n", "## Installation"]}, {"cell_type": "markdown", "id": "assisted-estate", "metadata": {}, "source": ["Install a Python module called the `pyyaml` to work with YAML files.\n", "\n", "```bash\n", "pip install pyyaml\n", "```"]}, {"cell_type": "markdown", "id": "fossil-strategy", "metadata": {}, "source": ["", "\n", "## Read YAML"]}, {"cell_type": "markdown", "id": "seventh-representation", "metadata": {}, "source": ["Let's create a simple yaml file first:"]}, {"cell_type": "code", "execution_count": 13, "id": "altered-gabriel", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["Writing learn_yaml.yaml\n"]}], "source": ["%%writefile learn_yaml.yaml\n", "message: Hello World"]}, {"cell_type": "markdown", "id": "worthy-expert", "metadata": {}, "source": ["You can read a yaml file with `yaml.load`:"]}, {"cell_type": "code", "execution_count": 2, "id": "drawn-effectiveness", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["Key: Value\n", "message: Hello World\n"]}], "source": ["import yaml\n", "\n", "with open(\"learn_yaml.yaml\", 'r') as f:\n", " yaml_content = yaml.load(f, yaml.SafeLoader)\n", "\n", "print(\"Key: Value\")\n", "for key, value in yaml_content.items():\n", " print(f\"{key}: {value}\")"]}, {"cell_type": "markdown", "id": "greatest-windows", "metadata": {}, "source": ["Also, `yaml.load` can read from a string:"]}, {"cell_type": "code", "execution_count": 16, "id": "hawaiian-pacific", "metadata": {}, "outputs": [{"data": {"text/plain": ["'this is'"]}, "execution_count": 16, "metadata": {}, "output_type": "execute_result"}], "source": ["yaml.load(\"this is\", Loader=yaml.SafeLoader)"]}, {"cell_type": "markdown", "id": "conceptual-processing", "metadata": {}, "source": ["Consider the following point number of \u201cpi\u201d, which has a value of 3.1415926. In YAML, it is represented as a floating number as shown below:"]}, {"cell_type": "code", "execution_count": 19, "id": "confident-istanbul", "metadata": {}, "outputs": [{"data": {"text/plain": ["float"]}, "execution_count": 19, "metadata": {}, "output_type": "execute_result"}], "source": ["yaml.load('3.1415926536', Loader=yaml.SafeLoader)"]}, {"cell_type": "markdown", "id": "going-suicide", "metadata": {}, "source": ["Suppose, multiple values are to be loaded in specific data structure as mentioned below:\n", "\n", "```\n", "eggs\n", "ham\n", "spam\n", "French basil salmon terrine\n", "```"]}, {"cell_type": "code", "execution_count": 15, "id": "purple-calculator", "metadata": {}, "outputs": [{"data": {"text/plain": ["['eggs', 'ham', 'spam', 'French basil salmon terrine']"]}, "execution_count": 15, "metadata": {}, "output_type": "execute_result"}], "source": ["yaml.load(\n", " \"\"\"\n", " - eggs\n", " - ham\n", " - spam\n", " - French basil salmon terrine\n", " \"\"\",\n", " Loader=yaml.SafeLoader\n", ")"]}, {"cell_type": "markdown", "id": "coral-interim", "metadata": {}, "source": ["**Note:** You can read on why calling `yaml.load` without `Loader` is deprecated in [here](https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation)"]}, {"cell_type": "markdown", "id": "breeding-still", "metadata": {}, "source": ["To make it easier through this section, we define and use this function to parse yaml strings:"]}, {"cell_type": "code", "execution_count": 2, "id": "coated-peoples", "metadata": {}, "outputs": [], "source": ["def read_yaml(string):\n", " return yaml.load(string, Loader=yaml.FullLoader)"]}, {"cell_type": "markdown", "id": "lovely-momentum", "metadata": {}, "source": ["", "\n", "## Introduction"]}, {"cell_type": "markdown", "id": "practical-perry", "metadata": {}, "source": ["Now that you have an idea about YAML and its features, let us learn its basics with syntax and other operations. Remember that YAML includes a human readable structured format."]}, {"cell_type": "markdown", "id": "enclosed-button", "metadata": {}, "source": ["", "\n", "### Rules for Creating YAML file\n", "\n", "When you are creating a file in YAML, you should remember the following basic rules:\n", "\n", "- YAML is case sensitive\n", "- The files should have `.yaml` or `.yml` as the extension\n", "- YAML does not allow the use of tabs while creating YAML files; spaces are allowed instead."]}, {"cell_type": "markdown", "id": "leading-gamma", "metadata": {}, "source": ["", "\n", "### Indentation of YAML\n", "\n", "YAML does not include any mandatory spaces. Further, there is no need to be consistent. The valid YAML indentation is shown below."]}, {"cell_type": "code", "execution_count": 9, "id": "small-screening", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'a': {'b': ['c', 'd', 'e']}, 'f': 'ghi'}"]}, "execution_count": 9, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\n", "\"\"\"\n", "a:\n", " b:\n", " - c\n", " - d\n", " - e\n", "f: \n", " \"ghi\"\n", "\"\"\"\n", ")"]}, {"cell_type": "markdown", "id": "governmental-sleeve", "metadata": {}, "source": ["You should remember the following rules while working with indentation in YAML:\n", "\n", "- Flow blocks must be intended with at least some spaces with surrounding current block level.\n", "- Flow content of YAML spans multiple lines. The beginning of flow content begins with `{` or `[`.\n", "- Block list items include same indentation as the surrounding block level because `-` is considered as a part of indentation."]}, {"cell_type": "markdown", "id": "thirty-empty", "metadata": {}, "source": ["", "\n", "### Basics Components"]}, {"cell_type": "markdown", "id": "average-potential", "metadata": {}, "source": ["The basic components of YAML are described below."]}, {"cell_type": "markdown", "id": "drawn-geometry", "metadata": {}, "source": ["", "\n", "#### Conventional Block Format\n", "This block format uses hyphen+space to begin a new item in a specified list. Observe the example shown below:"]}, {"cell_type": "code", "execution_count": 25, "id": "attached-journey", "metadata": {}, "outputs": [{"data": {"text/plain": ["['Casablanca', 'North by Northwest', \"The Man Who Wasn't There\"]"]}, "execution_count": 25, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\"\"\"\n", "# Favorite movies\n", "- Casablanca\n", "- North by Northwest\n", "- The Man Who Wasn't There\n", "\"\"\"\n", ")"]}, {"cell_type": "markdown", "id": "crazy-crystal", "metadata": {}, "source": ["**Note:** Comments in YAML begins with the `#` character. YAML does not support multi line comments."]}, {"cell_type": "markdown", "id": "economic-music", "metadata": {}, "source": ["", "\n", "#### Inline Format\n", "\n", "Inline format is delimited with comma and space and the items are enclosed in `JSON`. Observe the example shown below:"]}, {"cell_type": "code", "execution_count": 60, "id": "provincial-center", "metadata": {}, "outputs": [{"data": {"text/plain": ["['milk', 'groceries', 'eggs', 'juice', 'fruits']"]}, "execution_count": 60, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\"\"\"\n", "# Shopping list\n", "[milk, groceries, eggs, juice, fruits]\n", "\"\"\")"]}, {"cell_type": "code", "execution_count": 57, "id": "helpful-ordinary", "metadata": {}, "outputs": [{"data": {"text/plain": ["['milk', 'groceries', 'eggs', 'juice', 'fruits']"]}, "execution_count": 57, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(yaml_string)"]}, {"cell_type": "markdown", "id": "average-miami", "metadata": {}, "source": ["", "\n", "#### Folded Text\n", "\n", "Folded text converts newlines to spaces and removes the leading whitespace. Observe the example shown below:"]}, {"cell_type": "code", "execution_count": 59, "id": "explicit-military", "metadata": {}, "outputs": [{"data": {"text/plain": ["[{'name': 'John Smith', 'age': 33}, {'name': 'Mary Smith', 'age': 27}]"]}, "execution_count": 59, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\"\"\"\n", "- {name: John Smith, age: 33}\n", "- name: Mary Smith\n", " age: 27\n", "\"\"\")"]}, {"cell_type": "markdown", "id": "military-shift", "metadata": {}, "source": ["", "\n", "## YAML Syntax and format"]}, {"cell_type": "markdown", "id": "constant-spanish", "metadata": {}, "source": ["To begin with a YAML document, one needs to use `---`. All nested elements need to indented using two spaces but you can use one too. These three dashes are required only when there is more than one document within a single YAML file."]}, {"cell_type": "markdown", "id": "nutritional-timer", "metadata": {}, "source": ["", "\n", "### String"]}, {"cell_type": "markdown", "id": "atmospheric-sheffield", "metadata": {}, "source": ["", "\n", "#### Short texts\n", "Short texts are written, as shown below."]}, {"cell_type": "markdown", "id": "unlike-mason", "metadata": {}, "source": ["```yaml\n", "description: This is a brief description of something\n", "another description: \"This is also a short description with ':' in it.\"\n", "55.5 : keys need not be only strings\n", "```"]}, {"cell_type": "markdown", "id": "manual-reading", "metadata": {}, "source": ["", "\n", "#### Long text\n", "\n", "Long texts are written using `|` and `>`. A block written using `|` is called a literal block, and a block written with `>` is called a folded block."]}, {"cell_type": "markdown", "id": "talented-contact", "metadata": {}, "source": ["```yaml\n", "long description: |\n", "This text preserves the line breaks,\n", " as well as the indentation.\n", "folded long description: >\n", "This is also one way of writing the long text, but \n", " line breaks and indentations will be replaced with single spaces when read.\n", "```"]}, {"cell_type": "markdown", "id": "instrumental-bridges", "metadata": {}, "source": ["The block style indicates how newlines inside the block should behave. If you would like them to be kept as **newlines**, use the **literal style**, indicated by a **pipe** (`|`). If instead you want them to be **replaced by spaces**, use the **folded style**, indicated by a **right angle bracket** (`>`). (To get a newline using the folded style, leave a blank line by putting two newlines in. Lines with extra indentation are also not folded.)"]}, {"cell_type": "code", "execution_count": 14, "id": "ad65c2c3-3f31-4a1e-a342-53725219e93d", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'long description': 'This text preserves the line breaks,\\nas well as the indentation.\\n',\n", " 'folded long description': 'This is also one way of writing the long text, but line breaks and indentations will be replaced with single spaces when read.\\n'}"]}, "execution_count": 14, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\"\"\"\n", "long description: |\n", " This text preserves the line breaks,\n", " as well as the indentation.\n", "folded long description: >\n", " This is also one way of writing the long text, but \n", " line breaks and indentations will be replaced with single spaces when read.\n", "\"\"\"\n", ")"]}, {"cell_type": "markdown", "id": "waiting-evaluation", "metadata": {}, "source": ["", "\n", "### Numbers\n", "\n", "Integer numbers are written as shown below:\n", "\n", "```yaml\n", "canonical: 12345\n", "decimal: +12,345\n", "octal: 014\n", "hexadecimal: 0xC\n", "```"]}, {"cell_type": "markdown", "id": "informed-wrapping", "metadata": {}, "source": ["Float numbers are written as shown below:\n", "\n", "```yaml\n", "canonical: 1.23015e+3\n", "exponential: 12.3015e+02\n", "fixed: 1,230.15\n", "negative infinity: -.inf\n", "not a number: .NaN\n", "```"]}, {"cell_type": "markdown", "id": "resistant-greensboro", "metadata": {}, "source": ["", "\n", "### Boolean\n", "\n", "Boolean is written as true and false:\n", "\n", "```yaml\n", "flag: false\n", "not flag: true\n", "```"]}, {"cell_type": "markdown", "id": "radio-palace", "metadata": {}, "source": ["", "\n", "### Collections and Structures"]}, {"cell_type": "markdown", "id": "dated-photographer", "metadata": {}, "source": ["", "\n", "#### Lists\n", "\n", "YAML includes block collections which use indentation for scope. Here, each entry begins with a new line. Block sequences in collections indicate each entry with a dash and space (`-`). In YAML, block collections styles are not denoted by any specific indicator. Block collection in YAML can distinguished from other scalar quantities with an identification of key value pair included in them.\n", "\n", "Lists or arrays are written as shown below:\n", "\n", "```yaml\n", "simple list: [1, 2, 3, four, five, \u201cwith quotes\u201d]\n", "nested list:\n", " - item 1\n", " - item 2\n", " - \n", " - one\n", " - two\n", " - three\n", " - four\n", "```"]}, {"cell_type": "code", "execution_count": 58, "id": "exciting-repeat", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'simple list': [1, 2, 3, 'four', 'five', '\u201cwith quotes\u201d'],\n", " 'nested list': ['item 1', 'item 2', ['one', 'two', 'three', 'four']]}"]}, "execution_count": 58, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\n", "\"\"\"\n", "simple list: [1, 2, 3, four, five, \u201cwith quotes\u201d]\n", "nested list:\n", " - item 1\n", " - item 2\n", " - \n", " - one\n", " - two\n", " - three\n", " - four\n", "\"\"\")"]}, {"cell_type": "markdown", "id": "prescribed-miller", "metadata": {}, "source": ["", "\n", "### Maps\n", "\n", "Mappings are the representation of key value as included in JSON structure. It is used often in multi-lingual support systems and creation of API in mobile applications. Mappings use key value pair representation with the usage of colon and space (:).\n", "\n", "Maps can also be nested as shown below:\n", "\n", "```yaml\n", "This:\n", " is a:\n", " nested_map:\n", " key: value\n", "```"]}, {"cell_type": "code", "execution_count": 10, "id": "vital-advertiser", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'This': {'is a': {'nested_map': {'key': 'value'}}}}"]}, "execution_count": 10, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\n", "\"\"\"\n", "This:\n", " is a:\n", " nested_map:\n", " key: value\n", "\"\"\"\n", ")"]}, {"cell_type": "markdown", "id": "advisory-pottery", "metadata": {}, "source": ["", "\n", "### References\n", "\n", "References or anchors are useful when you want to copy an existing structure into a new form without repeating. An example is given below:"]}, {"cell_type": "code", "execution_count": 64, "id": "ambient-habitat", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'repeated text': 'This text need not be written again',\n", " 'an anchor': 'This text need not be written again',\n", " 'person': {'age': 10},\n", " 'member 1': {'age': 10, 'name': 'John'},\n", " 'member 2': {'age': 10, 'name': 'Dave'}}"]}, "execution_count": 64, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\n", "\"\"\"\n", "repeated text: &my_text This text need not be written again\n", "\n", "an anchor: *my_text\n", "\n", "# We can reference the maps too\n", "person: &person\n", " age: 10\n", "\n", "# All members below are of the same age\n", "member 1:\n", " <<: *person\n", " name: John\n", "member 2:\n", " <<: *person\n", " name: Dave\n", "\"\"\"\n", ")"]}, {"cell_type": "markdown", "id": "pleased-duncan", "metadata": {}, "source": ["", "\n", "### Multiple documents\n", "\n", "Three dashes `---`, mark the beginning of a new document"]}, {"cell_type": "code", "execution_count": 28, "id": "american-middle", "metadata": {}, "outputs": [], "source": ["# read_yaml(\n", "# \"\"\"\n", "# ---\n", "# message: Message of document one\n", "# ---\n", "# message: Message of document two\n", "# \"\"\"\n", "# )"]}, {"cell_type": "markdown", "id": "contained-gazette", "metadata": {}, "source": ["", "\n", "### Tags\n", "\n", "Tags, in YAML, are used to declare types. Examples are given below:"]}, {"cell_type": "code", "execution_count": 16, "id": "young-secretary", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'not a number': '0.00035',\n", " 'python tuple': (10, 1),\n", " 'an image': b'GIF89a\\x01\\x00\\x01\\x00\\x00\\x00\\x00!\\xf9\\x04\\x01\\n\\x00\\x01\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02L\\x01\\x00;'}"]}, "execution_count": 16, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\n", "\"\"\"\n", "not a number: !!str 0.00035\n", "\n", "python tuple: !!python/tuple [10,1]\n", "\n", "# An example of storing a binary file\n", "an image: !!binary |\n", " R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\n", "\"\"\"\n", ")"]}, {"cell_type": "code", "execution_count": 17, "id": "special-paradise", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'integer': '3', 'key': (1, 2)}"]}, "execution_count": 17, "metadata": {}, "output_type": "execute_result"}], "source": ["read_yaml(\n", "\"\"\"\n", "integer: !!str 3\n", "key: !!python/tuple [1, 2]\n", "\"\"\")"]}, {"cell_type": "code", "execution_count": null, "id": "00403ed3-b076-40df-a1f4-88f15ee1b569", "metadata": {}, "outputs": [], "source": []}], "metadata": {"kernelspec": {"display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.10"}}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file +{ + "cells": [ + { + "cell_type": "markdown", + "id": "11660a9b", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "floating-values", + "metadata": {}, + "source": [ + "# YAML \n" + ] + }, + { + "cell_type": "markdown", + "id": "58fe25c8", + "metadata": {}, + "source": [ + "## Table of Contents \n", + "* [YAML Tutorial Quick Start: A Simple File](#yaml_tutorial_quick_start:_a_simple_file)\n", + "* [Installation](#installation)\n", + "* [Read YAML](#read_yaml)\n", + "* [Introduction](#introduction)\n", + " * [Rules for Creating YAML file](#rules_for_creating_yaml_file)\n", + " * [Indentation of YAML](#indentation_of_yaml)\n", + " * [Basics Components](#basics_components)\n", + " * [Conventional Block Format](#conventional_block_format)\n", + " * [Inline Format](#inline_format)\n", + " * [Folded Text](#folded_text)\n", + "* [YAML Syntax and format](#yaml_syntax_and_format)\n", + " * [String](#string)\n", + " * [Short texts](#short_texts)\n", + " * [Long text](#long_text)\n", + " * [Numbers](#numbers)\n", + " * [Boolean](#boolean)\n", + " * [Collections and Structures](#collections_and_structures)\n", + " * [Lists](#lists)\n", + " * [Maps](#maps)\n", + " * [References](#references)\n", + " * [Multiple documents](#multiple_documents)\n", + " * [Tags](#tags)\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "contained-running", + "metadata": {}, + "source": [ + "**Y**AML **A**in't **M**arkup **L**anguage (**YAML**) is a serialization language that has steadily increased in popularity over the last few years. It's often used as a format for configuration files, but its object serialization abilities make it a viable replacement for languages like JSON. This YAML tutorial will demonstrate the language syntax with a guide and some simple coding examples in Python. YAML has broad language support and maps easily into native data structures. It's also easy to for humans to read, which is why it's a good choice for configuration. The YAML acronym was shorthand for **Yet Another Markup Language**. But the maintainers renamed it to **YAML Ain't Markup Language** to place more emphasis on its data-oriented features." + ] + }, + { + "cell_type": "markdown", + "id": "reasonable-proportion", + "metadata": {}, + "source": [ + "YAML is a recently introduced data serialization format and is very comfortable for human reading and writing. **YAML is poised to replace XML and JSON**." + ] + }, + { + "cell_type": "markdown", + "id": "apparent-makeup", + "metadata": {}, + "source": [ + "\n", + "## YAML Tutorial Quick Start: A Simple File" + ] + }, + { + "cell_type": "markdown", + "id": "intense-visitor", + "metadata": {}, + "source": [ + "Let's take a look at a YAML file for a brief overview." + ] + }, + { + "cell_type": "markdown", + "id": "tropical-chicken", + "metadata": {}, + "source": [ + "```yaml\n", + "---\n", + "quiz: \n", + " description: >\n", + " \"This Quiz is to learn YAML.\"\n", + " questions:\n", + " - [\"How many planets are there in the solar system?\", \"Name the non-planet\"]\n", + " - \"Who is found more on the web?\"\n", + " - \"What is the value of pi?\"\n", + " - \"Is pluto related to platonic relationships?\"\n", + " - \"How many maximum members can play TT?\"\n", + " - \"Which value is no value?\"\n", + " - \"Don't you know that the Universe is ever-expanding?\"\n", + " \n", + " answers:\n", + " - [8, \"pluto\"]\n", + " - cats\n", + " - 3.141592653589793\n", + " - true\n", + " - 4\n", + " - null\n", + " - no\n", + "# explicit data conversion and reusing data blocks\n", + "extra:\n", + " refer: &id011 # give a reference to data\n", + " x: !!float 5 # explicit conversion to data type float\n", + " y: 8\n", + " num1: !!int \"123\" # conversion to integer\n", + " str1: !!str 120 # conversion to string\n", + " again: *id011 # call data by giving the reference\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "cooperative-johns", + "metadata": {}, + "source": [ + "The identical `json` file is:" + ] + }, + { + "cell_type": "markdown", + "id": "expanded-amino", + "metadata": {}, + "source": [ + "```json\n", + "{\n", + " \"quiz\": {\n", + " \"description\": \"\\\"This Quiz is to learn YAML.\\\"\\n\",\n", + " \"questions\": [\n", + " [\n", + " \"How many planets are there in the solar system?\",\n", + " \"Name the non-planet\"\n", + " ],\n", + " \"Who is found more on the web?\",\n", + " \"What is the value of pi?\",\n", + " \"Is pluto related to platonic relationships?\",\n", + " \"How many maximum members can play TT?\",\n", + " \"Which value is no value?\",\n", + " \"Don't you know that the Universe is ever-expanding?\"\n", + " ],\n", + " \"answers\": [\n", + " [\n", + " 8,\n", + " \"pluto\"\n", + " ],\n", + " \"cats\",\n", + " 3.141592653589793,\n", + " true,\n", + " 4,\n", + " null,\n", + " false\n", + " ]\n", + " },\n", + " \"extra\": {\n", + " \"refer\": {\n", + " \"x\": 5.0,\n", + " \"y\": 8\n", + " },\n", + " \"num1\": 123,\n", + " \"str1\": \"120\",\n", + " \"again\": {\n", + " \"x\": 5.0,\n", + " \"y\": 8\n", + " }\n", + " }\n", + "}\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "alpine-center", + "metadata": {}, + "source": [ + "JSON and YAML have similar capabilities, and you can convert most documents between the formats." + ] + }, + { + "cell_type": "markdown", + "id": "equipped-police", + "metadata": {}, + "source": [ + "\n", + "## Installation" + ] + }, + { + "cell_type": "markdown", + "id": "assisted-estate", + "metadata": {}, + "source": [ + "Install a Python module called the `pyyaml` to work with YAML files.\n", + "\n", + "```bash\n", + "pip install pyyaml\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "fossil-strategy", + "metadata": {}, + "source": [ + "\n", + "## Read YAML" + ] + }, + { + "cell_type": "markdown", + "id": "seventh-representation", + "metadata": {}, + "source": [ + "Let's create a simple yaml file first:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "altered-gabriel", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing learn_yaml.yaml\n" + ] + } + ], + "source": [ + "%%writefile learn_yaml.yaml\n", + "message: Hello World" + ] + }, + { + "cell_type": "markdown", + "id": "worthy-expert", + "metadata": {}, + "source": [ + "You can read a yaml file with `yaml.load`:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "drawn-effectiveness", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Key: Value\n", + "message: Hello World\n" + ] + } + ], + "source": [ + "import yaml\n", + "\n", + "with open(\"learn_yaml.yaml\", 'r') as f:\n", + " yaml_content = yaml.load(f, yaml.SafeLoader)\n", + "\n", + "print(\"Key: Value\")\n", + "for key, value in yaml_content.items():\n", + " print(f\"{key}: {value}\")" + ] + }, + { + "cell_type": "markdown", + "id": "greatest-windows", + "metadata": {}, + "source": [ + "Also, `yaml.load` can read from a string:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "hawaiian-pacific", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'this is'" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "yaml.load(\"this is\", Loader=yaml.SafeLoader)" + ] + }, + { + "cell_type": "markdown", + "id": "conceptual-processing", + "metadata": {}, + "source": [ + "Consider the following point number of “pi”, which has a value of 3.1415926. In YAML, it is represented as a floating number as shown below:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "confident-istanbul", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3.1415926536" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "yaml.load('3.1415926536', Loader=yaml.SafeLoader)" + ] + }, + { + "cell_type": "markdown", + "id": "going-suicide", + "metadata": {}, + "source": [ + "Suppose, multiple values are to be loaded in specific data structure as mentioned below:\n", + "\n", + "```\n", + "eggs\n", + "ham\n", + "spam\n", + "French basil salmon terrine\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "purple-calculator", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['eggs', 'ham', 'spam', 'French basil salmon terrine']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "yaml.load(\n", + " \"\"\"\n", + " - eggs\n", + " - ham\n", + " - spam\n", + " - French basil salmon terrine\n", + " \"\"\",\n", + " Loader=yaml.SafeLoader\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "coral-interim", + "metadata": {}, + "source": [ + "**Note:** You can read on why calling `yaml.load` without `Loader` is deprecated in [here](https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation)" + ] + }, + { + "cell_type": "markdown", + "id": "breeding-still", + "metadata": {}, + "source": [ + "To make it easier through this section, we define and use this function to parse yaml strings:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "coated-peoples", + "metadata": {}, + "outputs": [], + "source": [ + "def read_yaml(string):\n", + " return yaml.load(string, Loader=yaml.FullLoader)" + ] + }, + { + "cell_type": "markdown", + "id": "lovely-momentum", + "metadata": {}, + "source": [ + "\n", + "## Introduction" + ] + }, + { + "cell_type": "markdown", + "id": "practical-perry", + "metadata": {}, + "source": [ + "Now that you have an idea about YAML and its features, let us learn its basics with syntax and other operations. Remember that YAML includes a human readable structured format." + ] + }, + { + "cell_type": "markdown", + "id": "enclosed-button", + "metadata": {}, + "source": [ + "\n", + "### Rules for Creating YAML file\n", + "\n", + "When you are creating a file in YAML, you should remember the following basic rules:\n", + "\n", + "- YAML is case sensitive\n", + "- The files should have `.yaml` or `.yml` as the extension\n", + "- YAML does not allow the use of tabs while creating YAML files; spaces are allowed instead." + ] + }, + { + "cell_type": "markdown", + "id": "leading-gamma", + "metadata": {}, + "source": [ + "\n", + "### Indentation of YAML\n", + "\n", + "YAML does not include any mandatory spaces. Further, there is no need to be consistent. The valid YAML indentation is shown below." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "small-screening", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'a': {'b': ['c', 'd', 'e']}, 'f': 'ghi'}" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "a:\n", + " b:\n", + " - c\n", + " - d\n", + " - e\n", + "f: \n", + " \"ghi\"\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "governmental-sleeve", + "metadata": {}, + "source": [ + "You should remember the following rules while working with indentation in YAML:\n", + "\n", + "- Flow blocks must be intended with at least some spaces with surrounding current block level.\n", + "- Flow content of YAML spans multiple lines. The beginning of flow content begins with `{` or `[`.\n", + "- Block list items include same indentation as the surrounding block level because `-` is considered as a part of indentation." + ] + }, + { + "cell_type": "markdown", + "id": "thirty-empty", + "metadata": {}, + "source": [ + "\n", + "### Basics Components" + ] + }, + { + "cell_type": "markdown", + "id": "average-potential", + "metadata": {}, + "source": [ + "The basic components of YAML are described below." + ] + }, + { + "cell_type": "markdown", + "id": "drawn-geometry", + "metadata": {}, + "source": [ + "\n", + "#### Conventional Block Format\n", + "This block format uses hyphen+space to begin a new item in a specified list. Observe the example shown below:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "attached-journey", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Casablanca', 'North by Northwest', \"The Man Who Wasn't There\"]" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\"\"\"\n", + "# Favorite movies\n", + "- Casablanca\n", + "- North by Northwest\n", + "- The Man Who Wasn't There\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "crazy-crystal", + "metadata": {}, + "source": [ + "**Note:** Comments in YAML begins with the `#` character. YAML does not support multi line comments." + ] + }, + { + "cell_type": "markdown", + "id": "economic-music", + "metadata": {}, + "source": [ + "\n", + "#### Inline Format\n", + "\n", + "Inline format is delimited with comma and space and the items are enclosed in `JSON`. Observe the example shown below:" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "id": "provincial-center", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['milk', 'groceries', 'eggs', 'juice', 'fruits']" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\"\"\"\n", + "# Shopping list\n", + "[milk, groceries, eggs, juice, fruits]\n", + "\"\"\")" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "id": "helpful-ordinary", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['milk', 'groceries', 'eggs', 'juice', 'fruits']" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(yaml_string)" + ] + }, + { + "cell_type": "markdown", + "id": "average-miami", + "metadata": {}, + "source": [ + "\n", + "#### Folded Text\n", + "\n", + "Folded text converts newlines to spaces and removes the leading whitespace. Observe the example shown below:" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "id": "explicit-military", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[{'name': 'John Smith', 'age': 33}, {'name': 'Mary Smith', 'age': 27}]" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\"\"\"\n", + "- {name: John Smith, age: 33}\n", + "- name: Mary Smith\n", + " age: 27\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "id": "military-shift", + "metadata": {}, + "source": [ + "\n", + "## YAML Syntax and format" + ] + }, + { + "cell_type": "markdown", + "id": "constant-spanish", + "metadata": {}, + "source": [ + "To begin with a YAML document, one needs to use `---`. All nested elements need to indented using two spaces but you can use one too. These three dashes are required only when there is more than one document within a single YAML file." + ] + }, + { + "cell_type": "markdown", + "id": "nutritional-timer", + "metadata": {}, + "source": [ + "\n", + "### String" + ] + }, + { + "cell_type": "markdown", + "id": "atmospheric-sheffield", + "metadata": {}, + "source": [ + "\n", + "#### Short texts\n", + "Short texts are written, as shown below." + ] + }, + { + "cell_type": "markdown", + "id": "unlike-mason", + "metadata": {}, + "source": [ + "```yaml\n", + "description: This is a brief description of something\n", + "another description: \"This is also a short description with ':' in it.\"\n", + "55.5 : keys need not be only strings\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "manual-reading", + "metadata": {}, + "source": [ + "\n", + "#### Long text\n", + "\n", + "Long texts are written using `|` and `>`. A block written using `|` is called a literal block, and a block written with `>` is called a folded block." + ] + }, + { + "cell_type": "markdown", + "id": "talented-contact", + "metadata": {}, + "source": [ + "```yaml\n", + "long description: |\n", + "This text preserves the line breaks,\n", + " as well as the indentation.\n", + "folded long description: >\n", + "This is also one way of writing the long text, but \n", + " line breaks and indentations will be replaced with single spaces when read.\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "instrumental-bridges", + "metadata": {}, + "source": [ + "The block style indicates how newlines inside the block should behave. If you would like them to be kept as **newlines**, use the **literal style**, indicated by a **pipe** (`|`). If instead you want them to be **replaced by spaces**, use the **folded style**, indicated by a **right angle bracket** (`>`). (To get a newline using the folded style, leave a blank line by putting two newlines in. Lines with extra indentation are also not folded.)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "ad65c2c3-3f31-4a1e-a342-53725219e93d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'long description': 'This text preserves the line breaks,\\nas well as the indentation.\\n',\n", + " 'folded long description': 'This is also one way of writing the long text, but line breaks and indentations will be replaced with single spaces when read.\\n'}" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\"\"\"\n", + "long description: |\n", + " This text preserves the line breaks,\n", + " as well as the indentation.\n", + "folded long description: >\n", + " This is also one way of writing the long text, but \n", + " line breaks and indentations will be replaced with single spaces when read.\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "waiting-evaluation", + "metadata": {}, + "source": [ + "\n", + "### Numbers\n", + "\n", + "Integer numbers are written as shown below:\n", + "\n", + "```yaml\n", + "canonical: 12345\n", + "decimal: +12,345\n", + "octal: 014\n", + "hexadecimal: 0xC\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "informed-wrapping", + "metadata": {}, + "source": [ + "Float numbers are written as shown below:\n", + "\n", + "```yaml\n", + "canonical: 1.23015e+3\n", + "exponential: 12.3015e+02\n", + "fixed: 1,230.15\n", + "negative infinity: -.inf\n", + "not a number: .NaN\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "resistant-greensboro", + "metadata": {}, + "source": [ + "\n", + "### Boolean\n", + "\n", + "Boolean is written as true and false:\n", + "\n", + "```yaml\n", + "flag: false\n", + "not flag: true\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "radio-palace", + "metadata": {}, + "source": [ + "\n", + "### Collections and Structures" + ] + }, + { + "cell_type": "markdown", + "id": "dated-photographer", + "metadata": {}, + "source": [ + "\n", + "#### Lists\n", + "\n", + "YAML includes block collections which use indentation for scope. Here, each entry begins with a new line. Block sequences in collections indicate each entry with a dash and space (`-`). In YAML, block collections styles are not denoted by any specific indicator. Block collection in YAML can distinguished from other scalar quantities with an identification of key value pair included in them.\n", + "\n", + "Lists or arrays are written as shown below:\n", + "\n", + "```yaml\n", + "simple list: [1, 2, 3, four, five, “with quotes”]\n", + "nested list:\n", + " - item 1\n", + " - item 2\n", + " - \n", + " - one\n", + " - two\n", + " - three\n", + " - four\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "id": "exciting-repeat", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'simple list': [1, 2, 3, 'four', 'five', '“with quotes”'],\n", + " 'nested list': ['item 1', 'item 2', ['one', 'two', 'three', 'four']]}" + ] + }, + "execution_count": 58, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "simple list: [1, 2, 3, four, five, “with quotes”]\n", + "nested list:\n", + " - item 1\n", + " - item 2\n", + " - \n", + " - one\n", + " - two\n", + " - three\n", + " - four\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "id": "prescribed-miller", + "metadata": {}, + "source": [ + "\n", + "### Maps\n", + "\n", + "Mappings are the representation of key value as included in JSON structure. It is used often in multi-lingual support systems and creation of API in mobile applications. Mappings use key value pair representation with the usage of colon and space (:).\n", + "\n", + "Maps can also be nested as shown below:\n", + "\n", + "```yaml\n", + "This:\n", + " is a:\n", + " nested_map:\n", + " key: value\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "vital-advertiser", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'This': {'is a': {'nested_map': {'key': 'value'}}}}" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "This:\n", + " is a:\n", + " nested_map:\n", + " key: value\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "advisory-pottery", + "metadata": {}, + "source": [ + "\n", + "### References\n", + "\n", + "References or anchors are useful when you want to copy an existing structure into a new form without repeating. An example is given below:" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "id": "ambient-habitat", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'repeated text': 'This text need not be written again',\n", + " 'an anchor': 'This text need not be written again',\n", + " 'person': {'age': 10},\n", + " 'member 1': {'age': 10, 'name': 'John'},\n", + " 'member 2': {'age': 10, 'name': 'Dave'}}" + ] + }, + "execution_count": 64, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "repeated text: &my_text This text need not be written again\n", + "\n", + "an anchor: *my_text\n", + "\n", + "# We can reference the maps too\n", + "person: &person\n", + " age: 10\n", + "\n", + "# All members below are of the same age\n", + "member 1:\n", + " <<: *person\n", + " name: John\n", + "member 2:\n", + " <<: *person\n", + " name: Dave\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "pleased-duncan", + "metadata": {}, + "source": [ + "\n", + "### Multiple documents\n", + "\n", + "Three dashes `---`, mark the beginning of a new document" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "american-middle", + "metadata": {}, + "outputs": [], + "source": [ + "document =\\\n", + "\"\"\"\n", + "---\n", + "message: Message of document one\n", + "---\n", + "message: Message of document two\n", + "\"\"\"" + ] + }, + { + "cell_type": "markdown", + "id": "f0914f3a-a04d-433e-991d-16eeb750d2b1", + "metadata": {}, + "source": [ + "If a string or a file contains several documents, you may load them all with the `yaml.load_all` function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e8058deb-4e5a-474a-90d3-69ae823199f7", + "metadata": {}, + "outputs": [], + "source": [ + "for data in yaml.load_all(documents): print data" + ] + }, + { + "cell_type": "markdown", + "id": "contained-gazette", + "metadata": {}, + "source": [ + "\n", + "### Tags\n", + "\n", + "Tags, in YAML, are used to declare types. Examples are given below:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "young-secretary", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'not a number': '0.00035',\n", + " 'python tuple': (10, 1),\n", + " 'an image': b'GIF89a\\x01\\x00\\x01\\x00\\x00\\x00\\x00!\\xf9\\x04\\x01\\n\\x00\\x01\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02L\\x01\\x00;'}" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "not a number: !!str 0.00035\n", + "\n", + "python tuple: !!python/tuple [10,1]\n", + "\n", + "# An example of storing a binary file\n", + "an image: !!binary |\n", + " R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "special-paradise", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'integer': '3', 'key': (1, 2)}" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "integer: !!str 3\n", + "key: !!python/tuple [1, 2]\n", + "\"\"\")" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "3c08e6b1-824e-43f2-a9fd-c4565431321e", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{None: 'value for null key',\n", + " 'complex': (2+3j),\n", + " 'Pluto is a planet': False,\n", + " 'negative': -1.0,\n", + " 'emoji': '🧨',\n", + " 'function yaml.dump': , **kwds)>}" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_yaml(\n", + "\"\"\"\n", + "!!null null: value for null key\n", + "\n", + "complex: !!python/complex 2+3j\n", + "\n", + "Pluto is a planet: !!bool \"false\" # boolean, because of !!bool\n", + "\n", + "negative: !!float -1\n", + "\n", + "emoji: !!python/unicode \"\\U0001F9E8\"\n", + "\n", + "function yaml.dump: !!python/name:yaml.dump\n", + "\"\"\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "1d3ce6eb-9c7e-4e7f-8dca-4c108449ca6e", + "metadata": {}, + "source": [ + "The following table describes how nodes with different tags are converted to Python objects:" + ] + }, + { + "cell_type": "markdown", + "id": "80c82e35-863c-4850-8f11-b276566f787e", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
YAML tagPython type
Standard YAML tags
!!nullNone
!!boolbool
!!intint or long (int in Python 3)
!!floatfloat
!!binarystr (bytes in Python 3)
!!timestampdatetime.datetime
!!omap, !!pairslist of pairs
!!setset
!!strstr or unicode (str in Python 3)
!!seqlist
!!mapdict
Python-specific tags
!!python/noneNone
!!python/boolbool
!!python/bytes(bytes in Python 3)
!!python/strstr (str in Python 3)
!!python/unicodeunicode (str in Python 3)
!!python/intint
!!python/longlong (int in Python 3)
!!python/floatfloat
!!python/complexcomplex
!!python/listlist
!!python/tupletuple
!!python/dictdict
Complex Python tags
!!python/name:module.namemodule.name
!!python/module:package.modulepackage.module
!!python/object:module.clsmodule.cls instance
!!python/object/new:module.clsmodule.cls instance
!!python/object/apply:module.fvalue of f(...)
" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dde0897e-a9bf-4ec5-b1ee-83a7d14c362f", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.10" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/01. Python/05. Modules/learn_yaml.yaml b/01. Python/05. Modules/learn_yaml.yaml new file mode 100644 index 0000000..add281c --- /dev/null +++ b/01. Python/05. Modules/learn_yaml.yaml @@ -0,0 +1 @@ +message: Hello World