# Copyright(C) 2010 Gribouillis, member of www.daniweb.com # licence: public domain # tested with python 2.6 and 3.1 from __future__ import print_function from contextlib import contextmanager @contextmanager def preferably(func, *args, **kwd): """Context to call a function in the end of a block of statement. func(*args, **kwd) will be called when the blocks exit unless the block raised an uncaugth exception.""" yield func(*args, **kwd) @contextmanager def inevitably(func, *args, **kwd): """Context to call a function in the end of a block of statement. func(*args, **kwd) will be called when the block exits even if the block raised an uncaught exception.""" try: yield finally: func(*args, **kwd) # EXAMPLE USE if __name__ == "__main__": import sys if sys.version_info < (3,): input = raw_input with preferably(print, "thank you for running this program."): # when this block exit, the above print will occur. name = input("please enter your name: ") print("hello", name, "!", "your named reversed is '%s'" % name[::-1] ,end=" ") input("<enter to continue>")
Are you able to help answer this sponsored question?
Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.