|
1 | 1 | from dataclasses import replace as slow_replace |
2 | 2 | import os |
3 | | -import typing |
| 3 | +from typing import Any, TypeVar |
4 | 4 |
|
5 | 5 |
|
6 | | -T = typing.TypeVar("T") |
| 6 | +T = TypeVar("T") |
7 | 7 |
|
8 | 8 |
|
9 | | -def fast_replace(arr: typing.Generic[T], **kwargs) -> T: |
| 9 | +def fast_replace(arr: T, **kwargs: Any) -> T: |
10 | 10 | """ |
11 | 11 | Fast replacement of dataclass fields with reduced safety. |
12 | 12 |
|
13 | 13 | Unlike dataclasses.replace, this function does not check for type compatibility, |
14 | 14 | nor does it check that the passed in fields are valid fields for the dataclass |
15 | 15 | and not flagged as init=False. |
16 | 16 |
|
| 17 | + BEWARE: This function is not type safe and may lead to runtime errors if |
| 18 | + used incorrectly. It implicitly assumes arr has a __dict__ attribute and |
| 19 | + that kwargs are valid init parameters for the dataclass of arr. |
| 20 | +
|
17 | 21 | User code may choose to use this replace or the legacy replace according to their needs. |
18 | 22 | To force ezmsg to use the legacy replace, set the environment variable: |
19 | 23 | EZMSG_DISABLE_FAST_REPLACE |
20 | 24 | Unset the variable to use this replace function. |
21 | 25 |
|
22 | 26 | :param arr: The dataclass instance to create a modified copy of. |
23 | | - :type arr: typing.Generic[T] |
| 27 | + :type arr: T |
24 | 28 | :param kwargs: Field values to update in the new instance. |
25 | 29 | :return: A new instance of the same type with updated field values. |
26 | 30 | :rtype: T |
27 | 31 | """ |
28 | 32 | out_kwargs = arr.__dict__.copy() # Shallow copy |
29 | | - out_kwargs.update(**kwargs) |
| 33 | + out_kwargs.update(kwargs) |
30 | 34 | return arr.__class__(**out_kwargs) |
31 | 35 |
|
32 | 36 |
|
|
0 commit comments