Skip to content
Snippets Groups Projects
Commit 715bc6b8 authored by Valentin Valls's avatar Valentin Valls
Browse files

Create a typed setting class

parent 23bc9df6
No related branches found
No related tags found
1 merge request!320Draft: Typed params
Pipeline #194581 failed
import enum
from tomo.helpers.typed_setting import settingclass
class EnumTest(enum.Enum):
FOO = 0
BAR = 1
BAZ = 2
@settingclass
class Foo:
foo1: str = "foo"
foo2: int = 10
foo3: float = 10.01
foo4: bool = True
foo5: EnumTest = EnumTest.FOO
def test_settingsclass(beacon, foo: str = "a"):
my_foo = Foo("my_foo")
print(my_foo)
assert my_foo.foo1 == "foo"
my_foo.foo1 = "fo"
assert my_foo.foo1 == "fo"
my_foo.foo1 = 1
my_foo.foo2 = 1
my_foo.foo3 = 1
my_foo.foo4 = False
my_foo.foo5 = EnumTest.BAR
import inspect
from pprint import pprint
from dataclasses import _get_field, _set_new_attribute, MISSING
from typing import Any
from bliss.config.settings import Struct
def _create_hash_setting_class(cls):
"""Create a HashSetting from a base class with annoatations"""
if hasattr(inspect, "get_annotations"):
cls_annotations = inspect.get_annotations(cls)
else:
# python <= 3.9
cls_annotations = cls.__dict__.get("__annotations__", {})
print()
default_values = {}
cls_fields = [_get_field(cls, name, type) for name, type in cls_annotations.items()]
pprint(cls_fields)
for f in cls_fields:
if f.default != MISSING:
default_values[f.name] = f.default
def init_fn(self, name: str, connection=None):
Struct.__init__(
self,
name=name,
connection=connection,
default_values=default_values,
)
_set_new_attribute(cls, "__init__", init_fn)
return cls
def settingclass(cls=None):
"""Add dunder methods based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine settings fields.
"""
def wrap(cls):
return _create_hash_setting_class(cls)
# See if we're being called as @settingclass or @settingclass().
if cls is None:
# We're called with parens.
return wrap
# We're called as @settingsclass without parens.
return wrap(cls)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment