SoFunction
Updated on 2024-11-12

Python with... .as... with...as... in Python

Synopsis:

  • withis fromPython2.5A new syntax has been introduced, which is a context management protocol designed to simplify flowcharts by removing the try, except, and finally keywords and resource allocation and release code from the flowchart.try….except….finlallyworkflow
  • withpass (a bill or inspection etc)__enter__method is initialized, and then the__exit__in doing the aftermath as well as handling exceptions. That's why it's a good idea to use thewithThe object being processed must have__enter__()cap (a poem)__exit__()Both methods.
  • with This statement is used when accessing a resource to ensure that the necessary "cleanup" operations are performed to free the resource regardless of whether an exception occurs during use, such as the automatic closing of a file after use, or the automatic acquisition and release of locks in a thread.

Examples are given below:

# Open the file and print out the contents of the file
with open('', 'r', encoding="utf-8") as f:
 print(()) 


Does this code look familiar? If it is, it is!

I. With... The basic syntax of the as statement.

with expression [as target]:
 with_body


Parameter Description:

expression:is an expression that needs to be executed;
target:is a variable or tuple that stores theexpressionThe result returned by the execution of the expression, [] indicates that the parameter is optional.

II. With... . as syntax execution process

  1. first runexpressionexpression, if the expression contains calculations, class initialization, etc., it will be executed first.
  2. (of a computer) run__enter()__Code in the method
  3. (of a computer) runwith_bodyembedded code
  4. (of a computer) run__exit()__The code in the method performs aftercare, such as freeing resources, handling errors, and so on.

III. Example validation

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
""" with... .as... Grammar Test """
__author__ = ""
__date__ = "2021/9/5"
__version__ = "1.1.0"
 
 
class testclass(object):
    def test(self):
        print("test123")
        print("")
 
 
class testwith(object):
    def __init__(self):
        print("Create the testwith class.")
        print("")
 
    def __enter__(self):
        print("Enter with . .as... before.")
        print("Create testclass entity")
        print("")
        tt = testclass()
        return tt
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exit with . .as...")
        print("Release testclass resources.")
        print("")
 
 
if __name__ == '__main__':
    with testwith() as t:
        print("with... . as... Program content")
        print("with_body")
        ()
 
 


IV. Results of the operation of the program

Create the testwith class
 
go to with... .as... before
Creating the testclass entity
 
with... .as... Program content
with_body
test123
 
withdraw with... .as...
Release testclass resources

V. Code Analysis

This code creates a total of 2 classes, the first onetestclassClasses are functional classes that are used to hold the definition of all the functions we need like the test() method here.
testwithclass is what we use to test thewith...as...syntax of the class used to give thetestclassclass for aftercare (releasing resources, etc.).

Program execution flow:


Up to this point this article onPythoncenterwith...as...The usage of the article is introduced to this, more relevantPythoncenterwith...as...For the usage of the content please search my previous articles or continue to browse the related articles below I hope you will support me more in the future!