How to Convert Strings to Types in Python Using TypeVar
A beginner-friendly helper that converts a string to int, float, bool, or str with type hints and graceful failure handling.
Python code
28 linesfrom typing import TypeVar, Optional
T = TypeVar("T")
def convert_data(value: str, target_type: type[T]) -> Optional[T]:
"""Convert string value to target type; return None on failure."""
try:
if target_type is int:
return int(value)
elif target_type is float:
return float(value)
elif target_type is bool:
return value.lower() in ("true", "1", "yes")
elif target_type is str:
return value
return None
except (ValueError, TypeError):
return None
if __name__ == "__main__":
# Simple test cases to demonstrate the converter
print(convert_data("42", int)) # 42
print(convert_data("3.14", float)) # 3.14
print(convert_data("true", bool)) # True
print(convert_data("hello", str)) # hello
print(convert_data("abc", int)) # None
print(convert_data("not-bool", bool)) # False
Output
42
3.14
True
hello
None
False
How it works
The TypeVar and type[T] syntax provide accurate type annotations so callers know what type will be returned. The function uses Optional[T] to signal that it can return None when conversion fails. The is checks compare the target type object directly, which works for built‑in types. Exception handling catches both ValueError and TypeError to cover invalid conversions. This pattern is ideal for parsing user input, configuration values, or query parameters.
Common mistakes
- Using `== int` instead of `is int` for built‑in types
- Forgetting to handle `TypeError` for non‑string inputs
- Not handling boolean variants like 'yes' or '1'
- Returning original string instead of `None` on failure
Variations
- Use `type(value).__name__` or a mapping dictionary for more complex type mappings
- Use `argparse` or `typing.Union` for more complex conversion scenarios
Real-world use cases
- Parsing CSV rows where columns arrive as strings and need type coercion before further processing.
- Reading environment variables or configuration file values that are always strings, converting them to expected types.
- Converting user form input or query parameters from HTTP requests into typed arguments for your application logic.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.