Conditions | 8 |
Total Lines | 51 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | |||
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: |
||
|
|||
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: |
||
41 | if value == arg: |
||
42 | return value |
||
43 | if isinstance(arg, type) and isinstance(value, arg): |
||
44 | return value |
||
45 | try: |
||
46 | return arg(value) |
||
47 | except (ValueError, TypeError): |
||
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 |