The with statement allows all sorts of syntactic sugar in python. This snippet defines two contexts: inevitably
and preferably
which register a function call to be executed at the end of a block of statement. Although they are not very useful (the function call could be written directly at the end of the block, or with the help of a try...finally
structure), some programmers may appreciate this style in certain circumstances.
Two amazing contexts.
# 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>")
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.