# func.py import sys import traceback # Displays error messages without the full stack trace def print_exception(tb): type, value = tb[:2] traceback.print_exception(type, value, None, 0) # Python function parameters must match arg list def f(x): print x f(1) try: f() except TypeError: print_exception(sys.exc_info()) print # Default args def check_password(password, numRetries=3, prompt='Enter password: '): for i in range(numRetries): input = raw_input(prompt) if input == password: return True return False print check_password('xyzzy', 1) print check_password('xyzzy', prompt='Password: ') print # Mutable defaults usually not wanted def f(a, b=[]): b.append(a) print b f(1) f('abc') # Better to use None and bind to a new list each time def f(a, b=None): if b is None: b = [] b.append(a) print b f(1) f('abc') print # *args is tuple; **kwargs is dict def f(*args, **kwargs): args = [repr(arg) for arg in args] print ', '.join(args) for key, value in kwargs.iteritems(): print "%s: %s" % (key, value) f(1, 2, 'abc', name='Joe', size=3.5) print # Can pass in *args and **kwargs def g(name, address, phone): print name print address print phone d = {'name':'Joe', 'address':'NY, NY', 'phone':'555-1212'} print d g(**d)