Python with keyword principle

HUIDBK 2021-04-07 12:34:26
python keyword principle

Python with Detailed explanation of keyword principle


When the correct handling involves exception Resource Management , Need to use try/finally The code structure , This kind of structure will lead to the overall code structure It's bloated and cumbersome , Not easy to read 、 Not beautiful , So in Python2.6 Version launch with keyword .

with as The sentence is Pyhton Provides a simplified Syntax , It is suitable for accessing resources , Make sure that the necessary... Is executed regardless of whether an exception occurs during use Cleanup operations , Release resources .

with Operation file

For system resources such as files 、 Database connection 、socket for , After the application opens these resources and executes the business logic , One of the things that has to be done is to close ( Release ) The resource .

such as Python The program opens a file , Write to a file , After you've written , Close the file , What happens if it's not shut down ? In extreme cases Too many open files Error of , Because the system allows you to open the maximum number of files is limited .

Again , For the database , If there are too many connections to close in time , It could happen Can not connect to MySQL server Too many connections, Because database connections are a very expensive resource , It is impossible to create indefinitely .

It's often seen in code that with open(file) as f Operate on files , among with What's the use of keywords ? Let's take a look at the underlying principles . See how to close a file properly .

Normal version :

file = "test.txt"

def fun1():
     Normal version

    f = open(file, "w")
    f.write("hello python")

There's a potential problem with writing this way , If you're calling write In the process of , An exception occurred that prevented subsequent code from executing ,close Method cannot be called properly , As a result, the resource is always released by the program's occupant . So how can you improve your code ?

premium :

file = "test.txt"

def fun2():
     exception handling

        f = open(file, "w")
        f.write("hello python")
    except Exception as e:

The modified version of the program is on the code where exceptions may occur try Capture , Use try/finally sentence , This statement indicates if in try There is an exception in the code block , Subsequent code is not executed , And jump straight to except Code block . And in any case ,finally The block's code will eventually be executed . therefore , Just put close Put it in finally In the code , The file must be closed .

premium :

file = "test.txt"

def fun3():
    with  keyword

    with open(file, "w"as f:
        f.write("hello python")

One is more concise 、 The elegant way is to use with keyword .open The return value of the method is assigned to the variable f, When leaving with Block of code , The system will call it automatically f.close() Method , with The role and use of try/finally The statement is the same . So how does it work ? Talking about with There is another concept involved before the principle of , Namely Context manager (Context Manager).

Context manager

What is context ?

Contexts mean different things in different places , Be sensible . In programming context The context is the environment .

for example One APP application , When switching interfaces , To save the information about which screen you jumped over and so on , So that when you click back you can jump right back , If you don't save the affirmation, you can't jump right back .

Another example is threads 、 When the coroutine switches tasks , How can a program know to switch to another task , Is it from the beginning or from the middle ? The context works , The task itself will preserve its environment , Where did it go , How much has been done , Various states identify records , So that's the context , So when switching, according to the context of each task , Carry on , So as to achieve multi task .

Context manager

Any class implements __enter__() and __exit__() Method objects can be called context managers .

The context manager object can be used with keyword .

file = "test.txt"

def fun3():
    with  keyword

    with open(file, "w"as f:
        # with  Code block
        f.write("hello python")
    print("with  End of sentence ")
  • __enter__(self): Automatically enter the context of the method call manager , The method will be in with as Code block Before execution . If with Statements are as Clause , Then the return value of this method will be assigned to as The variable after clause ; This method can return multiple values , So in as Clause can also be followed by multiple variables ( Multiple variables must be generated by () It's a tuple ).
  • __exit__(self, exc_type, exc_value, exc_traceback): Exit the method automatically called by the context manager . The method will be in with as Code block To execute after execution . If with as The successful execution of the code block ends , The program calls the method automatically , The three parameters to call this method are None, If with as Code block because Stop because of an exception , The program also calls the method automatically , Use sys.exc_info The obtained exception information will be used as the parameter to call the method .

Class based context manager

We can simulate implementing a file class of our own , Let the class implement __enter__() and __exit__() Method .

with The implementation principle of keywords
Context manager

#  Implement context manager based on class
class File(object):

    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
         Get into with as  The sentence is with call
         Return value as  as  The latter variable

        print("__enter__ called")
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, exc_traceback):
         Leave with The sentence is with call

        print("__exit__ called")
        print("exc_type: ", exc_type)
        print("exc_value: ", exc_value)
        print("exc_traceback: ", exc_traceback)
        print(" File close operation ")

def main():

    with File("test.txt""w"as f:
        print("with  Code block ")
        f.write("hello python1")
        f.write("hello python2")
        # a = 1 / 0
        f.write("hello python3")

    print("with  End of sentence ")

if __name__ == '__main__':

__enter__() Method returns a resource object , Here is the file object that you are going to open ,__exit__() Method handles some cleanup work .

because File Class implements the context manager , You can use it now with Statement . The operation results are as follows :

__enter__ called
with  Code block
__exit__ called
exc_type:  None
exc_value:  None
exc_traceback:  None
File close operation
with  End of sentence

hold except 0 abnormal Go and see the results

__enter__ called
with  Code block
__exit__ called
exc_type:  <class 'ZeroDivisionError'>
  division by zero
exc_traceback:  <traceback object at 0x0000021F0780BCC8>
File close operation
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\pycode\", line 113in <module>
  File "C:\Users\Administrator\Desktop\pycode\", line 106in main
    a = 1 / 0
ZeroDivisionError: division by zero

such , You don't have to call it explicitly close The method , By the system to call automatically , Even if there is an exception in the middle close Methods are also called .

be based on contextmanager Decorator

Python stay contextlib The module also provides a contextmanager The decorator , It further simplifies the way the context manager is implemented . adopt yield Split the function into two parts ,yield Before In the __enter__ Method execution ,yield after In the __exit__ Method execution . Keep up with the yield The following value is the return value of the function .

#  be based on contextmanager Decorator 
from contextlib import contextmanager

def file_manager(name, mode):
    print("file_manager() called")
        f = open(name, mode)
        yield f
        print(" File close operation ")


with file_manager('test.txt''w'as f:
        print("with  Code block ")
        f.write('hello world')
        # a = 1 / 0

print("with  End of sentence ")


file_manager() called
with  Code block
File close operation
with  End of sentence


Python Provides with Syntax is used to simplify subsequent cleanup of resource operations , yes try/finally Alternative methods , The implementation principle is based on the context manager . Besides ,Python One is also provided contextmanager Decorator , Further simplify the implementation of the context manager . Class based and contextmanager Context manager for , The two are identical in function . It's just , Class based context manager More flexible , Suitable for large-scale system development , And based on contextmanager Context manager for It is more convenient 、 concise , For small and medium-sized programs .

Whatever you use , Don't forget in the way __exit__() Or is it finally Free resources in block , This is especially important .

official account

New folder X

It took nature tens of billions of years to create our real world , And programmers use hundreds of years to create a completely different virtual world . We use the keyboard to make bricks and tiles , Build everything with your brain . People put 1000 Regard as authority , We do the opposite , defend 1024 The status of . We're not keyman , We are just the extraordinary creators of the ordinary world .


  1. Python brush questions - letter graphics
  2. Python数据分析入门(七):Pandas层级索引
  3. Introduction to Python data analysis (7): Pandas hierarchical index
  4. Python 操作腾讯云短信(sms)详细教程
  5. Python operation Tencent cloud SMS (SMS) detailed tutorial
  6. Python数据可视化,完整版实操指南 !
  7. Python data visualization, full version of the practical guide!
  8. 上手Pandas,带你玩转数据(2)-- 使用pandas从多种文件中读取数据
  9. 上手Pandas,带你玩转数据(1)-- 实例详解pandas数据结构
  10. Using pandas to read data from various files
  11. Hands on pandas, take you to play with data (1) -- detailed explanation of pandas data structure with examples
  12. Pandas数据结构基础用法
  13. Basic usage of pandas data structure
  14. Python读取ini配置文件,保存到对象属性
  15. Python reads the INI configuration file and saves it to the object properties
  16. Foundation of Python: classes in Python
  17. python刷题-闰年判断
  18. python刷题-01字串
  19. How to judge leap year
  20. Python brush title-01 string
  21. 安装python
  22. 按尺寸切片pandas数据集DataFrame到多个文件
  23. Install Python
  24. Slice the pandas dataset dataframe to multiple files by size
  25. python 求最大值、最小值、平均值
  26. Finding maximum, minimum and average in Python
  27. 认识Python解释器和PyCharm编辑器
  28. Know Python interpreter and pycharm editor
  29. Python 小数据池和代码块缓存机制
  30. Python small data pool and code block caching mechanism
  31. python刷题-序列求和
  32. python刷题-圆的面积
  33. Sequence summation in Python
  34. The area of a circle
  35. Python functions, advanced syntax and usage
  36. Teach you to crawl novels in Python! Who can pay for novels these days!
  37. Python入门学习之:10分钟1500访问量
  38. Introduction to Python: 1500 visits in 10 minutes
  39. 数据分析之Pandas合并操作总结
  40. OpenCV-Python 雪花飘落特效
  41. Pandas merge operation summary of data analysis
  42. Opencv Python snowflake falling effect
  43. python logging模块“另一个程序正在使用此文件,进程无法访问。”问题解决办法
  44. Python logging module "this file is being used by another program and cannot be accessed by the process." Problem solving
  45. Mac 下python3 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法
  46. Python 3 [SSL: Certificate] on MAC_ VERIFY_ Failed] certificate verify failed solution
  47. Python学习之解决python下载第三方依赖速度慢的问题
  48. Python learning to solve the problem of slow download speed of third party dependence on Python
  49. python操作Excel文件报lrd.biffh.XLRDError
  50. How to operate excel file with Python lrd.biffh.XLRDError
  51. 2021的挑战与机遇,今年Python数据分析岗位会很香!
  52. The challenge and opportunity of 2021, python data analysis post will be very popular this year!
  53. 【C++简明教程】Python和C++指定元素排序比较
  54. Comparison of Python and C + + specified element sorting
  55. Python Flask使用Nginx做代理时如何获取真实IP
  56. How to get real IP address when Python flash uses nginx as proxy
  57. Python培训出来好找工作吗?好找工作的关键是什么?
  58. Is Python training easy to find a job? What is the key to finding a good job?
  59. 从零开始学python | 什么是Python JSON?
  60. Learn Python from scratch | what is Python JSON?