跳转至

Variable

chanfig.Variable

Bases: Generic[V]

Mutable wrapper for immutable objects.

Parameters:

Name Type Description Default
value Any

The value to wrap.

Null
type type | None

Desired type of the value.

None
choices list | None

Possible values of the value.

None
validator Callable | None

Callable that validates the value.

None
required bool

Whether the value is required.

False
help str | None

Help message of the value.

None

Raises:

Type Description
RuntimeError

If required is True and value is Null.

TypeError

If type is specified and value is not an instance of type.

ValueError

| If choices is specified and value is not in choices. If validator is specified and validator returns False.

Attributes:

Name Type Description
value Any

The wrapped value.

dtype type

The type of the wrapped value.

Notes

Variable by default wrap the instance type to type of the wrapped object. Therefore, isinstance(Variable(1), int) will return True.

To temporarily disable this behaviour, you can call context manager with Variable.unwrapped().

To permanently disable this behaviour, you can call Variable.unwrap().

Examples:

Python Console Session
>>> v = Variable(1)
>>> n = v
>>> v, n
(1, 1)
>>> v += 1
>>> v, n
(2, 2)
>>> v.value = 3
>>> v, n
(3, 3)
>>> n.set(4)
>>> v, n
(4, 4)
>>> n = 5
>>> v, n
(4, 5)
>>> f'{v} < {n}'
'4 < 5'
>>> isinstance(v, int)
True
>>> type(v)
<class 'chanfig.variable.Variable'>
>>> v.dtype
<class 'int'>
>>> with v.unwrapped():
...    isinstance(v, int)
False
>>> v = Variable('hello')
>>> f'{v}, world!'
'hello, world!'
>>> v += ', world!'
>>> v
'hello, world!'
>>> "hello" in v
True
Source code in chanfig/variable.py
Python
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
class Variable(Generic[V]):  # pylint: disable=R0902
    r"""
    Mutable wrapper for immutable objects.

    Args:
        value: The value to wrap.
        type: Desired type of the value.
        choices: Possible values of the value.
        validator: `Callable` that validates the value.
        required: Whether the value is required.
        help: Help message of the value.

    Raises:
        RuntimeError: If `required` is `True` and `value` is `Null`.
        TypeError: If `type` is specified and `value` is not an instance of `type`.
        ValueError: |
            If `choices` is specified and `value` is not in `choices`.
            If `validator` is specified and `validator` returns `False`.

    Attributes:
        value: The wrapped value.
        dtype: The type of the wrapped value.

    Notes:
        `Variable` by default wrap the instance type to type of the wrapped object.
        Therefore, `isinstance(Variable(1), int)` will return `True`.

        To temporarily disable this behaviour, you can call context manager `with Variable.unwrapped()`.

        To permanently disable this behaviour, you can call `Variable.unwrap()`.

    Examples:
        >>> v = Variable(1)
        >>> n = v
        >>> v, n
        (1, 1)
        >>> v += 1
        >>> v, n
        (2, 2)
        >>> v.value = 3
        >>> v, n
        (3, 3)
        >>> n.set(4)
        >>> v, n
        (4, 4)
        >>> n = 5
        >>> v, n
        (4, 5)
        >>> f'{v} < {n}'
        '4 < 5'
        >>> isinstance(v, int)
        True
        >>> type(v)
        <class 'chanfig.variable.Variable'>
        >>> v.dtype
        <class 'int'>
        >>> with v.unwrapped():
        ...    isinstance(v, int)
        False
        >>> v = Variable('hello')
        >>> f'{v}, world!'
        'hello, world!'
        >>> v += ', world!'
        >>> v
        'hello, world!'
        >>> "hello" in v
        True
    """

    wrap_type: bool = True
    _storage: List[Any]
    _type: Optional[type] = None
    _choices: Optional[list] = None
    _validator: Optional[Callable] = None
    _required: bool = False
    _help: Optional[str] = None

    def __init__(  # pylint: disable=R0913
        self,
        value: Any = Null,
        type: type | None = None,  # pylint: disable=W0622
        choices: list | None = None,
        validator: Callable | None = None,
        required: bool = False,
        help: str | None = None,  # pylint: disable=W0622
    ) -> None:
        self._storage = [value]
        self._type = type
        self._choices = choices
        self._validator = validator
        self._required = required
        self._help = help

    @property  # type: ignore[misc]
    def __class__(self) -> type:
        return self.value.__class__ if self.wrap_type else type(self)

    @property
    def value(self) -> Any:
        r"""
        Fetch the object wrapped in `Variable`.
        """

        return self._storage[0]

    @value.setter
    def value(self, value) -> None:
        r"""
        Assign value to the object wrapped in `Variable`.
        """

        self.validate(value)
        self._storage[0] = self._get_value(value)

    @property
    def dtype(self) -> type:
        r"""
        Data type of the object wrapped in `Variable`.

        Examples:
            >>> id = Variable(1016)
            >>> type(id)
            <class 'chanfig.variable.Variable'>
            >>> id.dtype
            <class 'int'>
            >>> issubclass(id.dtype, int)
            True
        """

        return self.value.__class__

    @property
    def storage(self) -> list[Any]:
        r"""
        Storage of `Variable`.
        """

        return self._storage

    @property
    def type(self) -> type | None:
        return self._type

    @property
    def choices(self) -> list | None:
        return self._choices

    @property
    def validator(self) -> Callable | None:
        return self._validator

    @property
    def required(self) -> bool:
        return self._required

    @property
    def help(self) -> str:
        return self._help or ""

    def validate(self, *args) -> None:
        r"""
        Validate if the value is valid.
        """

        if len(args) == 0:
            value = self.value
        elif len(args) == 1:
            value = args[0]
        else:
            raise ValueError("Too many arguments.")
        if self._required and value is Null:
            raise RuntimeError("Value is required.")
        if self._type is not None and not isinstance(value, self._type):
            raise TypeError(f"Value {value} is not of type {self._type}.")
        if self._choices is not None and value not in self._choices:
            raise ValueError(f"Value {value} is not in choices {self._choices}.")
        if self._validator is not None and not self._validator(value):
            raise ValueError(f"Value {value} is not valid.")

    def get(self) -> Any:
        r"""
        Fetch the object wrapped in `Variable`.
        """

        return self.value

    def set(self, value) -> None:
        r"""
        Assign value to the object wrapped in `Variable`.

        `Variable.set` is extremely useful when you want to change the value without changing the reference.

        In `FlatDict.set`, all assignments of `Variable` calls `Variable.set` Internally.
        """

        self.value = value

    def __get__(self, obj, objtype=None):
        return self

    def __set__(self, obj, value):
        self.value = value

    def to(self, cls: Callable) -> Any:  # pylint: disable=C0103
        r"""
        Convert the object wrapped in `Variable` to target `cls`.

        Args:
            cls: The type to convert to.

        Examples:
            >>> id = Variable(1016)
            >>> id.to(float)
            1016.0
            >>> id.to(str)
            '1016.0'
        """

        self.value = cls(self.value)
        return self

    def int(self) -> int:
        r"""
        Convert the object wrapped in `Variable` to python `int`.

        Examples:
            >>> id = Variable(1016.0)
            >>> id.int()
            1016
        """

        return self.to(int)

    def float(self) -> float:
        r"""
        Convert the object wrapped in `Variable` to python `float`.

        Examples:
            >>> id = Variable(1016)
            >>> id.float()
            1016.0
        """

        return self.to(float)

    def str(self) -> str:
        r"""
        Convert the object wrapped in `Variable` to python `float`.

        Examples:
            >>> id = Variable(1016)
            >>> id.str()
            '1016'
        """

        return self.to(str)

    def wrap(self) -> None:
        r"""
        Wrap the type of `Variable`.

        Examples:
            >>> id = Variable(1016)
            >>> id.unwrap()
            >>> isinstance(id, int)
            False
            >>> id.wrap()
            >>> isinstance(id, int)
            True
        """

        self.wrap_type = True

    def unwrap(self) -> None:
        r"""
        Unwrap the type of `Variable`.

        Examples:
            >>> id = Variable(1016)
            >>> id.unwrap()
            >>> isinstance(id, int)
            False
        """

        self.wrap_type = False

    @contextmanager
    def unwrapped(self):
        r"""
        Context manager which temporarily unwrap the `Variable`.

        Examples:
            >>> id = Variable(1016)
            >>> isinstance(id, int)
            True
            >>> with id.unwrapped():
            ...    isinstance(id, int)
            False
        """

        wrap_type = self.wrap_type
        self.wrap_type = False
        try:
            yield self
        finally:
            self.wrap_type = wrap_type

    @staticmethod
    def _get_value(obj) -> Any:
        if isinstance(obj, Variable):
            return obj.value
        return obj

    def __getattr__(self, attr) -> Any:
        return getattr(self.value, attr)

    def __lt__(self, other) -> bool:
        return self.value < self._get_value(other)

    def __le__(self, other) -> bool:
        return self.value <= self._get_value(other)

    def __eq__(self, other) -> bool:
        return self.value == self._get_value(other)

    def __ne__(self, other) -> bool:
        return self.value != self._get_value(other)

    def __ge__(self, other) -> bool:
        return self.value >= self._get_value(other)

    def __gt__(self, other) -> bool:
        return self.value > self._get_value(other)

    # def __index__(self):
    #     return self.value.__index__()

    def __invert__(self):
        return ~self.value

    def __abs__(self):
        return abs(self.value)

    def __add__(self, other):
        return Variable(self.value + self._get_value(other))

    def __radd__(self, other):
        return Variable(self._get_value(other) + self.value)

    def __iadd__(self, other):
        self.value += self._get_value(other)
        return self

    def __and__(self, other):
        return Variable(self.value & self._get_value(other))

    def __rand__(self, other):
        return Variable(self._get_value(other) & self.value)

    def __iand__(self, other):
        self.value &= self._get_value(other)
        return self

    def __floordiv__(self, other):
        return Variable(self.value // self._get_value(other))

    def __rfloordiv__(self, other):
        return Variable(self._get_value(other) // self.value)

    def __ifloordiv__(self, other):
        self.value //= self._get_value(other)
        return self

    def __mod__(self, other):
        return Variable(self.value % self._get_value(other))

    def __rmod__(self, other):
        return Variable(self._get_value(other) % self.value)

    def __imod__(self, other):
        self.value %= self._get_value(other)
        return self

    def __mul__(self, other):
        return Variable(self.value * self._get_value(other))

    def __rmul__(self, other):
        return Variable(self._get_value(other) * self.value)

    def __imul__(self, other):
        self.value *= self._get_value(other)
        return self

    def __matmul__(self, other):
        return Variable(self.value @ self._get_value(other))

    def __rmatmul__(self, other):
        return Variable(self._get_value(other) @ self.value)

    def __imatmul__(self, other):
        self.value @= self._get_value(other)
        return self

    def __pow__(self, other):
        return Variable(self.value ** self._get_value(other))

    def __rpow__(self, other):
        return Variable(self._get_value(other) ** self.value)

    def __ipow__(self, other):
        self.value **= self._get_value(other)
        return self

    def __truediv__(self, other):
        return Variable(self.value / self._get_value(other))

    def __rtruediv__(self, other):
        return Variable(self._get_value(other) / self.value)

    def __itruediv__(self, other):
        self.value /= self._get_value(other)
        return self

    def __sub__(self, other):
        return Variable(self.value - self._get_value(other))

    def __rsub__(self, other):
        return Variable(self._get_value(other) - self.value)

    def __isub__(self, other):
        self.value -= self._get_value(other)
        return self

    def __copy__(self):
        return Variable(self.value)

    def __deepcopy__(self, memo: Mapping | None = None):
        return Variable(copy(self.value))

    def __format__(self, format_spec):
        return self.value if isinstance(self, str) else format(self.value, format_spec)

    def __iter__(self):
        return iter(self.value)

    def __next__(self):
        return next(self.value)

    def __hash__(self):
        return hash(self.value)

    def __repr__(self):
        return repr(self.value)

    def __str__(self):
        return self.value if isinstance(self, str) else str(self.value)

    def __json__(self):
        return self.value

    def __contains__(self, name):
        return name in self.value

value property writable

Python
value: Any

Fetch the object wrapped in Variable.

dtype property

Python
dtype: type

Data type of the object wrapped in Variable.

Examples:

Python Console Session
>>> id = Variable(1016)
>>> type(id)
<class 'chanfig.variable.Variable'>
>>> id.dtype
<class 'int'>
>>> issubclass(id.dtype, int)
True

storage property

Python
storage: list[Any]

Storage of Variable.

validate

Python
validate(*args) -> None

Validate if the value is valid.

Source code in chanfig/variable.py
Python
def validate(self, *args) -> None:
    r"""
    Validate if the value is valid.
    """

    if len(args) == 0:
        value = self.value
    elif len(args) == 1:
        value = args[0]
    else:
        raise ValueError("Too many arguments.")
    if self._required and value is Null:
        raise RuntimeError("Value is required.")
    if self._type is not None and not isinstance(value, self._type):
        raise TypeError(f"Value {value} is not of type {self._type}.")
    if self._choices is not None and value not in self._choices:
        raise ValueError(f"Value {value} is not in choices {self._choices}.")
    if self._validator is not None and not self._validator(value):
        raise ValueError(f"Value {value} is not valid.")

get

Python
get() -> Any

Fetch the object wrapped in Variable.

Source code in chanfig/variable.py
Python
def get(self) -> Any:
    r"""
    Fetch the object wrapped in `Variable`.
    """

    return self.value

set

Python
set(value) -> None

Assign value to the object wrapped in Variable.

Variable.set is extremely useful when you want to change the value without changing the reference.

In FlatDict.set, all assignments of Variable calls Variable.set Internally.

Source code in chanfig/variable.py
Python
def set(self, value) -> None:
    r"""
    Assign value to the object wrapped in `Variable`.

    `Variable.set` is extremely useful when you want to change the value without changing the reference.

    In `FlatDict.set`, all assignments of `Variable` calls `Variable.set` Internally.
    """

    self.value = value

to

Python
to(cls: Callable) -> Any

Convert the object wrapped in Variable to target cls.

Parameters:

Name Type Description Default
cls Callable

The type to convert to.

required

Examples:

Python Console Session
>>> id = Variable(1016)
>>> id.to(float)
1016.0
>>> id.to(str)
'1016.0'
Source code in chanfig/variable.py
Python
def to(self, cls: Callable) -> Any:  # pylint: disable=C0103
    r"""
    Convert the object wrapped in `Variable` to target `cls`.

    Args:
        cls: The type to convert to.

    Examples:
        >>> id = Variable(1016)
        >>> id.to(float)
        1016.0
        >>> id.to(str)
        '1016.0'
    """

    self.value = cls(self.value)
    return self

int

Python
int() -> int

Convert the object wrapped in Variable to python int.

Examples:

Python Console Session
>>> id = Variable(1016.0)
>>> id.int()
1016
Source code in chanfig/variable.py
Python
def int(self) -> int:
    r"""
    Convert the object wrapped in `Variable` to python `int`.

    Examples:
        >>> id = Variable(1016.0)
        >>> id.int()
        1016
    """

    return self.to(int)

float

Python
float() -> float

Convert the object wrapped in Variable to python float.

Examples:

Python Console Session
>>> id = Variable(1016)
>>> id.float()
1016.0
Source code in chanfig/variable.py
Python
def float(self) -> float:
    r"""
    Convert the object wrapped in `Variable` to python `float`.

    Examples:
        >>> id = Variable(1016)
        >>> id.float()
        1016.0
    """

    return self.to(float)

str

Python
str() -> str

Convert the object wrapped in Variable to python float.

Examples:

Python Console Session
>>> id = Variable(1016)
>>> id.str()
'1016'
Source code in chanfig/variable.py
Python
def str(self) -> str:
    r"""
    Convert the object wrapped in `Variable` to python `float`.

    Examples:
        >>> id = Variable(1016)
        >>> id.str()
        '1016'
    """

    return self.to(str)

wrap

Python
wrap() -> None

Wrap the type of Variable.

Examples:

Python Console Session
>>> id = Variable(1016)
>>> id.unwrap()
>>> isinstance(id, int)
False
>>> id.wrap()
>>> isinstance(id, int)
True
Source code in chanfig/variable.py
Python
def wrap(self) -> None:
    r"""
    Wrap the type of `Variable`.

    Examples:
        >>> id = Variable(1016)
        >>> id.unwrap()
        >>> isinstance(id, int)
        False
        >>> id.wrap()
        >>> isinstance(id, int)
        True
    """

    self.wrap_type = True

unwrap

Python
unwrap() -> None

Unwrap the type of Variable.

Examples:

Python Console Session
>>> id = Variable(1016)
>>> id.unwrap()
>>> isinstance(id, int)
False
Source code in chanfig/variable.py
Python
def unwrap(self) -> None:
    r"""
    Unwrap the type of `Variable`.

    Examples:
        >>> id = Variable(1016)
        >>> id.unwrap()
        >>> isinstance(id, int)
        False
    """

    self.wrap_type = False

unwrapped

Python
unwrapped()

Context manager which temporarily unwrap the Variable.

Examples:

Python Console Session
>>> id = Variable(1016)
>>> isinstance(id, int)
True
>>> with id.unwrapped():
...    isinstance(id, int)
False
Source code in chanfig/variable.py
Python
@contextmanager
def unwrapped(self):
    r"""
    Context manager which temporarily unwrap the `Variable`.

    Examples:
        >>> id = Variable(1016)
        >>> isinstance(id, int)
        True
        >>> with id.unwrapped():
        ...    isinstance(id, int)
        False
    """

    wrap_type = self.wrap_type
    self.wrap_type = False
    try:
        yield self
    finally:
        self.wrap_type = wrap_type