Skip to content

Instantly share code, notes, and snippets.

@mjuenema
Created July 24, 2017 00:22
Show Gist options
  • Save mjuenema/d1ca8cfdb1d437b4947e82837d60fe9c to your computer and use it in GitHub Desktop.
Save mjuenema/d1ca8cfdb1d437b4947e82837d60fe9c to your computer and use it in GitHub Desktop.

Python decorator example

def typecheck(type_):
    def decorator_(func):
    
        def wrapper_(name):
           if not type(name) == type_:
               raise TypeError
           else:
               return func(name)
        
        return wrapper_
        
    return decorator_

@typecheck(str)
def f_str(v):
    print('str ' + v)

@typecheck(int)
def f_int(v):
    print('int ' + str(v))


f_str('a string')
f_int(1)
f_str(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment