agronholm / typeguard

Run-time type checker for Python
Other
1.52k stars 114 forks source link

Enable typecheck_fail_callback to return a value #458

Open decision-dev opened 5 months ago

decision-dev commented 5 months ago

Things to check first

Feature description

Currently typecheck_fail_callback can only be used for side effects. I am proposing that it should also be able to return a value and that check_type would then return that value.

Use case

This lets us replace this:

x = None
try: 
   check_type(<value>,  <type>)
except TypeCheckError as err:
   x = some_function(err, z)

with the much cleaner and more elegant:

x = check_type(<value>,  <type>,  typecheck_fail_callback= partial(some_function, arg=z)