From 9ef0fab1e2c848411e966966118fd2a8d3327511 Mon Sep 17 00:00:00 2001 From: Shane Smiskol Date: Thu, 8 Aug 2024 20:49:47 -0700 Subject: [PATCH] okay actually not bad --- .../car/data_test_kinda_works_chatgpt.py | 47 +++++++------------ 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/selfdrive/car/data_test_kinda_works_chatgpt.py b/selfdrive/car/data_test_kinda_works_chatgpt.py index be6ddd2406..83804c0670 100644 --- a/selfdrive/car/data_test_kinda_works_chatgpt.py +++ b/selfdrive/car/data_test_kinda_works_chatgpt.py @@ -1,44 +1,33 @@ # import attr from dataclasses import dataclass, field from typing import Any, List +from enum import auto -class AutoDefault: - """Marker class for fields that should automatically get a default.""" - def __init__(self, factory: Any = None): - self.factory = factory +auto_obj = object() -def auto_factory(factory=None): - """Function to return AutoDefault instance.""" - return AutoDefault(factory=factory) def apply_auto_defaults(cls): - cls_annotations = cls.__annotations__ - for name, typ in cls_annotations.items(): - current_value = getattr(cls, name, None) - if isinstance(current_value, AutoDefault): - if current_value.factory is not None: - setattr(cls, name, field(default_factory=current_value.factory)) - else: - # Handle specific default types here or raise an error - setattr(cls, name, field(default_factory=typ)) - # if typ == bool: - # setattr(cls, name, attr.field(default=False)) - # elif typ == list: - # setattr(cls, name, attr.field(factory=list)) - # elif typ == dict: - # setattr(cls, name, attr.field(factory=dict)) - # else: - # raise ValueError(f"No default or factory defined for type {typ}") - return cls + cls_annotations = cls.__annotations__ + for name, typ in cls_annotations.items(): + current_value = getattr(cls, name, None) + if current_value is auto_obj: + setattr(cls, name, field(default_factory=typ)) + return cls + + +def auto_factory(): + return auto_obj + @dataclass @apply_auto_defaults class CarControl: - enabled: bool = auto_factory() # Automatically get a default of False - pts: list[int] = auto_factory() # Automatically get an empty list as the default + enabled: bool = auto_factory() + pts: list[int] = auto_factory() + logMonoTime: list[int] = field(default_factory=lambda: [1, 2, 3]) # This will now work with default values set by the decorator -car_control_instance = CarControl(enabled=True,) +car_control_instance = CarControl() print(car_control_instance.enabled) # Should print False -print(car_control_instance.pts) # Should print [] +print(car_control_instance.pts) # Should print []