The Safe Caster

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3

Problem

Only 'int', 'float' and 'bool' are supported targets, and an unsupported type_name or a value that won't convert must come back as None instead of crashing the loader. An engineer cleaning raw fields from an upstream export needs safe_cast to convert value to the type type_name names, following Python's own casting rules.

Type conversion is easy, until it is not.

Example 1

Input:

value = "42", type_name = "int"

Output:

42

Example 2

Input:

value = "hello", type_name = "int"

Output:

null

Worked solution and explanation

Why this problem exists in real interviews

This is an allow-list gate that looks like a type conversion. Anyone can wrap a cast in try/except. The real point is that the three supported names are a fixed set, and that set is checked before any cast runs. So 'str' comes back None even though str(42) would succeed without complaint. Resolve type_name through eval or a builtins lookup and every builtin type gets past the gate, and callers who rely on None to catch a bad target end up accepting whatever the export sends.


Break down the requirements

Step 1: Map type strings to Python type constructors

Map the three allowed names to int, float and bool. Turn away any other type_name with an early return None before the value is touched, so the lookup that follows can never miss.

Step 2: Attempt the cast inside try/except

Put only the cast inside try/except Exception. int('hello') raises ValueError and int(None) raises TypeError. Both mean the field is bad, so both return None. Keeping the lookup outside the try means the guard clause, not the handler, is what rejects an unknown type name.

Step 3: Return the cast value on success

If no exception occurs, return the result.


The solution

Dispatch with try/except for safe casting
def safe_cast(value, type_name):
    type_map = {
        'int': int,
        'float': float,
        'bool': bool,
    }
    if type_name not in type_map:
        return None

    cast = type_map[type_name]
    try:
        return cast(value)
    except Exception:
        return None

Common follow-up questions