Files
example-code-2e/08-def-type-hints/typeddict/books.py
2020-06-11 14:58:15 -03:00

32 lines
813 B
Python

# tag::BOOKDICT[]
from typing import TypedDict, List
import json
class BookDict(TypedDict):
isbn: str
title: str
authors: List[str]
pagecount: int
# end::BOOKDICT[]
# tag::TOXML[]
AUTHOR_EL = '<AUTHOR>{}</AUTHOR>'
def to_xml(book: BookDict) -> str: # <1>
elements: List[str] = [] # <2>
for key, value in book.items():
if isinstance(value, list): # <3>
elements.extend(
AUTHOR_EL.format(n) for n in value) # <4>
else:
tag = key.upper()
elements.append(f'<{tag}>{value}</{tag}>')
xml = '\n\t'.join(elements)
return f'<BOOK>\n\t{xml}\n</BOOK>'
# end::TOXML[]
# tag::FROMJSON[]
def from_json(data: str) -> BookDict:
whatever: BookDict = json.loads(data) # <1>
return whatever # <2>
# end::FROMJSON[]