1 | |||
2 | |||
3 | def typechain(*args): |
||
4 | """ |
||
5 | Returns function which applies the first transformation it can from args |
||
6 | and returns transformed value, or the value itself if it is in args. |
||
7 | |||
8 | >>> function = typechain(int, 'a', ord, None) |
||
9 | >>> function("10") |
||
10 | 10 |
||
11 | >>> function("b") |
||
12 | 98 |
||
13 | >>> function("a") |
||
14 | 'a' |
||
15 | >>> function(int) |
||
16 | <class 'int'> |
||
17 | >>> function(None) is None |
||
18 | True |
||
19 | >>> function("str") |
||
20 | Traceback (most recent call last): |
||
21 | ... |
||
22 | ValueError: Couldn't convert value 'str' to any specified type or find it \ |
||
23 | in specified values. |
||
24 | |||
25 | :raises TypeError: Raises when either no functions are specified for |
||
26 | checking. |
||
27 | """ |
||
28 | if len(args) == 0: |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
![]() |
|||
29 | raise TypeError("No arguments were provided.") |
||
30 | |||
31 | def annotation(value): |
||
32 | """ |
||
33 | Returns value either transformed with one of the function in args, or |
||
34 | casted to one of types in args, or the value itself if it is in the |
||
35 | args. |
||
36 | |||
37 | :raises ValueError: Raises when cannot transform value in any one of |
||
38 | specified ways. |
||
39 | """ |
||
40 | for arg in args: |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
|
|||
41 | if value == arg: |
||
42 | return value |
||
43 | if isinstance(arg, type) and isinstance(value, arg): |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
|
|||
44 | return value |
||
45 | try: |
||
46 | return arg(value) |
||
47 | except (ValueError, TypeError): |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
Comprehensibility
Best Practice
introduced
by
|
|||
48 | pass |
||
49 | raise ValueError( |
||
50 | "Couldn't convert value {value} to any specified type " |
||
51 | "or find it in specified values.".format( |
||
52 | value=repr(value))) |
||
53 | return annotation |
||
54 |