|
1 |
| -from dataclasses import dataclass, field |
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import InitVar, dataclass, field |
2 | 4 | from typing import Any, ClassVar, Dict, Generic, List, Optional, Set, TypeVar, Union
|
3 | 5 |
|
4 | 6 | from openapi_python_client import utils
|
@@ -222,20 +224,40 @@ def get_imports(self, *, prefix: str) -> Set[str]:
|
222 | 224 | return imports
|
223 | 225 |
|
224 | 226 |
|
| 227 | +_existing_enums: Dict[str, EnumProperty] = {} |
| 228 | + |
| 229 | + |
225 | 230 | @dataclass
|
226 | 231 | class EnumProperty(Property):
|
227 | 232 | """ A property that should use an enum """
|
228 | 233 |
|
229 | 234 | values: Dict[str, str]
|
230 |
| - reference: Reference |
| 235 | + reference: Reference = field(init=False) |
| 236 | + title: InitVar[str] |
231 | 237 |
|
232 | 238 | template: ClassVar[str] = "enum_property.pyi"
|
233 | 239 |
|
234 |
| - def __post_init__(self) -> None: |
| 240 | + def __post_init__(self, title: str) -> None: # type: ignore |
235 | 241 | super().__post_init__()
|
| 242 | + reference = Reference.from_ref(title) |
| 243 | + dedup_counter = 0 |
| 244 | + while reference.class_name in _existing_enums: |
| 245 | + existing = _existing_enums[reference.class_name] |
| 246 | + if self.values == existing.values: |
| 247 | + break # This is the same Enum, we're good |
| 248 | + dedup_counter += 1 |
| 249 | + reference = Reference.from_ref(f"{reference.class_name}{dedup_counter}") |
| 250 | + |
| 251 | + self.reference = reference |
236 | 252 | inverse_values = {v: k for k, v in self.values.items()}
|
237 | 253 | if self.default is not None:
|
238 | 254 | self.default = f"{self.reference.class_name}.{inverse_values[self.default]}"
|
| 255 | + _existing_enums[self.reference.class_name] = self |
| 256 | + |
| 257 | + @staticmethod |
| 258 | + def get_all_enums() -> Dict[str, EnumProperty]: |
| 259 | + """ Get all the EnumProperties that have been registered keyed by class name """ |
| 260 | + return _existing_enums |
239 | 261 |
|
240 | 262 | def get_type_string(self) -> str:
|
241 | 263 | """ Get a string representation of type that should be used when declaring this property """
|
@@ -345,7 +367,7 @@ def property_from_dict(name: str, required: bool, data: Dict[str, Any]) -> Prope
|
345 | 367 | name=name,
|
346 | 368 | required=required,
|
347 | 369 | values=EnumProperty.values_from_list(data["enum"]),
|
348 |
| - reference=Reference.from_ref(data.get("title", name)), |
| 370 | + title=data.get("title", name), |
349 | 371 | default=data.get("default"),
|
350 | 372 | )
|
351 | 373 | if "$ref" in data:
|
|
0 commit comments