Main Content
with in Python - examples of use, and of defining your own context Archive - Originally posted on "The Horse's Mouth" - 2016-11-02 01:12:45 - Graham Ellis
The with keyword in Python lets you set up an object with a block scope and a defined closure. It's implemented in the standard file handle object library - see example at [here] and you can implement it for your own object using the __enter__ and __exit__ methods - example [here] . Note that the __exit__ method differs from the usual descructor in that you get to choose via your scope the point at which you release the data within your object, and (alas) the object isn't actuall destroyed in that the name does not go out of scope.
class trackorder(object):
def __init__(self,top):
self.values = range(1,top+1)
def __enter__(self):
return self
def __exit__(self,a,b,c):
self.values = []
# Big list in "trax" while it's used
with trackorder(7) as trax:
print(trax)
for t in trax.values:
print(t)
print("Length within block: " + str(len(trax.values)))
# gone away outside the "with" area
print("Length outside block: " + str(len(trax.values)))
Inside the block, the length reports a 7 element long list held in the trackorder object; upon exit from the block, this has been reduced to a list of zero length, though the name and object still exist.
Some other articles
Y112 - Objects - Intermediate Nesting decorators Defining an object that is a modified standard type in Python This article Object and Static methods - what is the difference; example in Python 3 Setting up and tearing down with the Python with keyword Deciding whether to use parameters, conditional statements or subclasses Spike solution, refactoring into encapsulated object methods - good design practise A good example of recursion - a real use in Python Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Python base and inherited classes, test harness and unit testing - new examples Python Properties - how and why Really Simple Class and Inheritance example in Python Inheritance, Composition and Associated objects - when to use which - Python example Backquote, backtic, str and repr in Python - conversion object to string Metaclasses (Python) and Metatables (Lua) Static variables in functions - and better ways using objects A demonstration of how many Python facilities work together A list of special method and attribute names in Python Python - some common questions answered in code examples Defining static methods in Python Should Python classes each be in their own file? The Light bulb moment when people see how Object Orientation works in real use Python decorators - your own, staticmethod and classmethod Mixins example in Python Multiple inheritance in Python - complete working example The Multiple Inheritance Conundrum, interfaces and mixins Methods that run on classes (static methods) in Python How do I set up a constant in Python? TypeError: super() argument 1 must be type, not classobj (Python) Python - fresh examples of all the fundamentals Calling base class constructors Equality, sameness and identity - Python Using a utility method to construct objects of different types - Python Python - formatting objects What are factory and singleton classes? __new__ v __init__ - python constructor alternatives? Practical polymorphism in action Pieces of Python Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML Class, static and unbound variables Overloading of operators on standard objects in Python Using a Python dictionary as a holder of object attributes Y110 - File Handling This article Scons - a build system in Python - building hello world Easy data to object mapping (csv and Python) Command line parameter handling in Python via the argparse module Running an operating system command from your Python program - the new way with the subprocess module Loving programming in Python - and ready to teach YOU how Shell, Awk, Perl of Python? Python or Lua - which should I use / learn? How can I do an FTP transfer in Python? A demonstration of how many Python facilities work together Python - fresh examples from recent courses Old prices - what would the equivalent price have been in 1966? Checking robots.txt from Python Conversion of OSI grid references to Eastings and Northings Reading a file multiple times - file pointers The elegance of Python Relative or absolute milkman