~jasper/type_stack_calc

ref: 6aca66fb1a7cf1e10f7dd3263f04537c8ff37590 type_stack_calc/type_stack_calc/base/with_params.py -rw-r--r-- 1.4 KiB
6aca66fb — Jasper den Ouden Apparently `to_c` can already read ahead one, hopefully its this simple... 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#  Copyright (C) 2021 Jasper den Ouden.
#
#  This is free software: you can redistribute it and/or modify
#  it under the terms of the Affero GNU General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.

from inspect import signature

from type_stack_calc.ib.plain_component import PlainComponent

class WithParams:
    """Helper providing `.get_param` method from `param_...` methods, and possibly `.get_param_final`."""

    callable_cls = None

    def get_param(self, key):
        # NOTE: it gets the value of the `type` of itself! Otherwise it'll fill in the first value!
        param = getattr(type(self), f"param_{key}", None)
        if param is None:
            param = getattr(self, f"param_{key}", None)

        if callable(param):  # Assume it's an plain inbuild function.
            args = list(signature(param).parameters)
            # InbuildFunction
            return self.callable_cls(args, param, key)
        elif param is not None:
            return param

        assert getattr(self, 'get_param_final', None), \
            f"Don't have param `{key}` in {self}({type(self)}) and no alternative getter" \
            + str(dir(self))
        return self.get_param_final(key)

    def get_comp(self, name):
        val = self.get_param(name)
        if notify := getattr(val, 'notify_name', None): notify(name)
        return PlainComponent(name, val)