okay actually not bad

pull/33208/head
Shane Smiskol 9 months ago
parent 7795697983
commit 9ef0fab1e2
  1. 47
      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 []

Loading…
Cancel
Save