CodexBloom - Programming Q&A Platform

Python 3.10 Type Hinting with Union and Optional Causes Confusion in Function Signature

πŸ‘€ Views: 76 πŸ’¬ Answers: 1 πŸ“… Created: 2025-05-31
python type-hinting optional Python

I'm converting an old project and I tried several approaches but none seem to work. I've hit a wall trying to I'm sure I'm missing something obvious here, but I'm trying to write a function in Python 3.10 that accepts either an integer or None, and I want to use type hinting to make that clear..... However, I'm running into issues with how to properly annotate the function signature using `Union` and `Optional`. Here’s the function I'm working with: ```python from typing import Optional def process_value(value: Optional[int]) -> str: if value is None: return 'No value provided' return f'Processing value: {value}' ``` When I run this function with a `None` value, it works as expected: ```python result = process_value(None) print(result) # Output: No value provided ``` However, I got an unexpected behavior when I tried to pass a string instead: ```python result = process_value('string') ``` This raises a `TypeError`: ``` TypeError: process_value() argument must be int or None, not str ``` I expected this to be caught at the type hinting level, but it seems that Python is only enforcing type checks at runtime and not during development. Is there a way to make this type hinting more robust or to ensure that my function only accepts the intended types at the development stage? I've also tried using `Union[int, None]` instead of `Optional[int]`, but the behavior seems to be the same. Any insights on how to handle this more elegantly would be appreciated! For context: I'm using Python on Linux. I'd really appreciate any guidance on this. For context: I'm using Python on macOS. Has anyone else encountered this? What are your experiences with this? I'm working with Python in a Docker container on macOS. Any feedback is welcome! Has anyone else encountered this?