Fix typing.Optional normalization.

This commit is contained in:
Alex RootJunior 2019-06-30 23:12:13 +03:00
parent af2573dbee
commit 43c565d39b
4 changed files with 326 additions and 318 deletions

View file

@ -37,12 +37,10 @@ def normalize_type_annotation(item: dict):
@functools.lru_cache()
def normalize_type(string, required=True):
def normalize_type(string):
if not string:
return "typing.Any"
union = "typing.Union" if required else "typing.Optional"
lower = string.lower()
split = lower.split()
@ -52,7 +50,7 @@ def normalize_type(string, required=True):
if "or" in split:
split_types = string.split(" or ")
norm_str = ", ".join(map(normalize_type, map(str.strip, split_types)))
return f"{union}[{norm_str}]"
return f"typing.Union[{norm_str}]"
if "number" in lower:
return normalize_type(string.replace("number", "").strip())
if lower in ["true", "false"]:
@ -83,3 +81,12 @@ def get_returning(description):
break
return return_type, sentence + "."
def normalize_optional(python_type: str, required: bool = True) -> str:
if not required:
if "typing.Union" in python_type:
python_type = python_type.replace("typing.Union", "typing.Optional")
else:
python_type = f"typing.Optional[{python_type}]"
return python_type

View file

@ -3,7 +3,7 @@ from __future__ import annotations
import typing
from dataclasses import dataclass, field
from generator.normalizers import normalize_type, get_returning
from generator.normalizers import normalize_type, get_returning, normalize_optional
@dataclass
@ -21,10 +21,11 @@ class Annotation:
@property
def python_type(self) -> str:
return normalize_type(self.type, self.required)
result = normalize_type(self.type)
return normalize_optional(result, self.required)
@property
def python_argument(self):
def python_field(self):
result = f"{self.python_name}: {self.python_type}"
value = "" if self.required else "None"

View file

@ -5,7 +5,7 @@ class {{ entity.python_name }}(pydantic.BaseModel):
Source: https://core.telegram.org/bots/api#{{ entity.anchor }}
"""
{% for annotation in entity.annotations %}
{{ annotation.python_argument }}
{{ annotation.python_field }}
"""{{ annotation.description|indent(width=4) }}"""
{% else %}
pass