Skip to content

PyYAML

the home of various YAML implementations for Python.

How to install

$ sudo pip install pyyaml

loads

python의 json.loads와 비슷한 함수를 사용하고 싶다면 full_load 함수를 사용하면 된다.

from yaml import full_load

a = """
data:
  - a
  - b
"""

print(full_load(a))

Enhance list indentation

다음과 같이 list 가 상위 depth 의 indent 로 출력될 경우:

>>> d = {'a': [1, 2, 3]}
>>> print(yaml.safe_dump(d))
a:
- 1
- 2
- 3

다음과 같이 Dumper 를 재정의:

class IndentDumper(yaml.Dumper):
    def increase_indent(self, flow=False, indentless=False):
        return super(IndentDumper, self).increase_indent(flow, False)

다음과 같이 list 에 indent 가 매겨져서 출력된다:

>>> print(yaml.dump(d, Dumper=IndentDumper))
a:
  - 1
  - 2
  - 3

단락별 New Line

다음과 같이 단락 이 다닥다닥 붙어있다면:

a:
  b: []
c:
  d: []

Dumper 재정의

class NewLineDumper(Dumper):
    def write_line_break(self, data: Optional[str] = None) -> None:
        super().write_line_break(data)
        if self.indent == ROOT_INDENT:
            super().write_line_break(data)

다음과 같이 출력된다:

a:
  b: []

c:
  d: []

Troubleshooting

덤프(Dump)시 중첩 컬렉션 오작동

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

다음과 같이 출력된다.

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

기본적으로 PyYAML은 중첩 된 컬렉션이 있는지 여부에 따라 컬렉션의 스타일을 선택합니다. 컬렉션에 중첩 된 컬렉션이있는 경우 block-style이 지정됩니다. 그렇지 않으면 flow-style을 갖게됩니다.

컬렉션이 항상 블록 스타일로 직렬화되도록하려면 dump()default_flow_style 매개 변수를 False로 설정합니다.

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

See also

Favorite site