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.

Easy Python 3.10+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

28 lines
Python 3.10+
from 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

stdout
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

  1. Use `type(value).__name__` or a mapping dictionary for more complex type mappings
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.