# The Safe Caster

> Type conversion is easy, until it is not.

Canonical URL: <https://datadriven.io/problems/the_safe_caster>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a value and a type_str in ('int', 'float', 'bool'), return the value cast to that type. If the cast raises any exception, return None instead.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **exception handling and type dispatch** in Python. It checks whether candidates can map type names to callables, attempt a cast, and return None gracefully on failure.

---

### Break down the requirements

#### Step 1: Map type strings to Python type constructors

Create a dispatch dict: `'int'` to `int`, `'float'` to `float`, `'bool'` to `bool`.

#### Step 2: Attempt the cast inside try/except

Call the constructor on the value. If it raises any exception, catch it and return None.

#### Step 3: Return the cast value on success

If no exception occurs, return the result.

---

### The solution

**Dispatch with try/except for safe casting**

```python
def safe_cast(value, type_name):
    type_map = {
        'int': int,
        'float': float,
        'bool': bool,
    }
    if type_name not in type_map:
        return None
    try:
        result = type_map[type_name](value)
        return result
    except Exception:
        return None
```

> **Time and Space Complexity**
>
> **Time:** O(1). Type conversion is constant time for simple types.
> 
> **Space:** O(1). No data structures beyond the dispatch dict.

> **Interviewers Watch For**
>
> Do you use `except Exception` instead of a bare `except`? Catching `Exception` is best practice; bare `except` catches `SystemExit` and `KeyboardInterrupt` which should propagate.

> **Common Pitfall**
>
> Not handling `bool` correctly. In Python, `bool('False')` returns `True` because any non-empty string is truthy. The problem may accept this, but mentioning it shows awareness.

---

## Common follow-up questions

- What if you needed to support custom types? _(Tests extending the dispatch dict or accepting a callable.)_
- How would you handle bool('False') returning True? _(Tests adding special-case logic for string-to-bool conversion.)_
- What if the type_name were invalid? _(Tests returning None or raising a ValueError for unknown types.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_safe_caster)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.