PI. Extended example of with statement

Run Settings
LanguagePython
Language Version
Run Command
# Here's we create a simple class to serve us (inpired by "Rick and Morty" # butter-giving robot). It does nothing, but take the orders and executes them. class Servant(object): def __init__(self, farewell="It was pleasure to serve you!", commandor="lord"): self.farewell = farewell self.commandor = commandor self.orders = [] def sentence(self, order): self.orders.append(order) def execute(self): for order in self.orders: print "In the name of my {commandor}! {sentence}!".format( sentence=order, commandor=self.commandor ) self.orders = [] def __del__(self): if self.orders: print "My {commandor}, you never told me to execute those {number} task(s)".format( commandor = self.commandor, number = len(self.orders) ) print self.farewell # Lets test the power of our words and make some orders servant = Servant() servant.sentence("Bring me a bread") servant.sentence("Squeeze me fresh juice out of thoughts of my people") servant.execute() # As you see this order left without being executed, so our servant will complain # at the end. servant.sentence("Reveal yourself") # But let us have another servant that will do all our orders without being asked. # We will place him in the context of 'with' to denote that we want this all orders # be executed no matter what! class ContextedServant(Servant): # Describe the behaviour on entrance into with-statement and return operable # object to deal with in this context. def __enter__(self): print "I'm your servant till the end of my bits!" return self # Describe behaviour on exit event. exc_* variables describe exception in # the context if happend. def __exit__(self, exc_type, exc_val, exc_tb): self.execute() # Give him some orders, but do not tell him to execute them directly. with ContextedServant(commandor="earl") as context_servant: context_servant.sentence("Give me butter") print "Looks like we're done..." # Everyhting were done!
Editor Settings
Theme
Key bindings
Full width
Lines