Skip to content

Instantly share code, notes, and snippets.

@nulldatamap
Created June 29, 2014 14:01
Show Gist options
  • Select an option

  • Save nulldatamap/04a9491e3f5e56a4329c to your computer and use it in GitHub Desktop.

Select an option

Save nulldatamap/04a9491e3f5e56a4329c to your computer and use it in GitHub Desktop.
doTypecheck = True
def typecheck( f ):
def wrapper( *args ):
global doTypecheck
if doTypecheck:
sig = signature( f )
for k, p in zip( args, sig.parameters.keys() ):
pv = sig.parameters[p]
if type( k ) != pv and not isinstance( k, pv ):
raise TypeError( "The type of parameter '{}' for function '{}', didn't match the " +
"expected type '{}' ( got '{}' )".format( p, f.__name__, pv, type( k ) ))
r = f( *args )
if type( r ) != sig.return_annotation and not isinstance( r, sig.return_annotation ):
raise TypeError( "The returned value from '{}' didn't match the expected type '{}'" +
" ( got '{}' )".format( f.__name__, sig.return_annotation, type( r ) ) )
return r
else:
return f( *args )
return wrapper
@typecheck
def myFunc( x : int, y : str, z : object ) -> Exception:
return IOError( "Test" )
raise myFunc( 13, "wow", 9.0 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment