Given string n, cast to specified type and return. Warns and returns None if this fails
(n: str, cast_type: type)
| 62 | |
| 63 | |
| 64 | def try_cast_from_str(n: str, cast_type: type): |
| 65 | """ |
| 66 | Given string n, cast to specified type and return. Warns and returns None |
| 67 | if this fails |
| 68 | """ |
| 69 | if cast_type not in (str, int, float, list): |
| 70 | return None |
| 71 | |
| 72 | try: |
| 73 | if cast_type == str: |
| 74 | return str(n) |
| 75 | elif cast_type == int: |
| 76 | return int(n) |
| 77 | elif cast_type == float: |
| 78 | return float(n) |
| 79 | elif cast_type == list: |
| 80 | return ast.literal_eval(n) |
| 81 | except (ValueError, SyntaxError, TypeError, MemoryError, RecursionError): |
| 82 | return None |
no outgoing calls
no test coverage detected
searching dependent graphs…