Introduction to context manager in Python 3

fengbingchun 2021-10-29 06:14:49
introduction context manager python

      In any programming language , The use of resources such as file operations or database connections is common . But the supply of these resources is limited . therefore , The main problem is to ensure that these resources are released after use . If you don't release them , It will lead to resource leakage , And may cause the system to slow down or crash . If the user has a mechanism to automatically set and disassemble resources , This will be very helpful . stay Python3 in , You can use the context manager (context manager) To achieve , This helps to properly handle resources . The context manager is an object .

      stay Python3 in , You can manage resources through the context manager . There are three ways to create a context manager : Class based context manager 、 Generator based context manager and function decorator based context manager .

      When creating a context manager using a class , Users need to ensure that this class has __enter__() and __exit__() Method .__enter__() Return the resources to be managed ; and __exit__() Don't return anything , Instead, perform cleanup operations .

      Context managers usually use with The statement calls , But they can also be used by calling their methods directly . The context manager defines the context in which with The runtime context to build at statement time , It handles incoming (entry into) And exit (exit from) The required runtime context to execute the code block .

      The most common way to perform file operations is to use with keyword .Python Of with Statement supports the concept of runtime context defined by the context manager . This is using a pair of methods (__enter__, __exit__) Realized , These methods allow user-defined classes to enter the runtime context before the statement body is executed and exit at the end of the statement .

      with grammar :

with EXPRESSION [as TARGET]:
SUITE

      with The execution of the statement is as follows

      (1). Evaluate the context expression to get the context manager ;

      (2). Of the context manager __enter__() Loaded for later use ;

      (3). Of the context manager __exit__() Loaded for later use ;

      (4). Of the context manager __enter__() Method is called ;

      (5). If TARGET Included in with In the sentence , Will __enter__() Assign to it the return value of .with The statement guarantees if __enter__() Method returns no error , that __exit__() Will always be called . therefore , If assigned to TARGET An error occurred during the list , It will be seen as SUITE What happened in .__enter__() Methods can either have a return value or no return value , If there is no return value, it will return... By default None.

      (6).SUITE Be performed ;

      (7). Of the context manager __exit__() Method is called . If the exception causes SUITE sign out , Then its type 、 Value and backtracking (traceback) Pass as a parameter to __exit__(); otherwise , Pass on 3 individual None.__exit__() Methods can also have return values , This return value should be a boolean type True or False, The default is None( namely False). If False, Exception will be thrown , Users need to handle exceptions . If True, The exception is ignored .

      If SUITE Exit due to exception , also __exit__() The value returned by the method is False, The exception is triggered . If the return value is True, The anomaly is suppressed , And continue with Statement after statement .

      If SUITE Exit for any reason other than exception , be __exit__() The return value of will be ignored , And continue at the normal position of the exit type taken .

      contextmanager.__enter__(): Enter the runtime context and return this object or another object related to the runtime context . The value returned by this method is bound to... Using this context manager with Of the statement as The target specified in clause ( If there is ). An example of a context manager that returns itself is a file object . File object from __enter__() Return to itself to allow open() Used as a with The context expression in the statement .

      contextmanager.__exit__(exc_type, exc_val, exc_tb): Exits the runtime context and returns a boolean flag , Indicates whether any exceptions that occur should be suppressed . If in execution with An exception occurred while the body of the statement , The parameter contains the exception type 、 Values and backtracking information (traceback information). otherwise , All three parameters are None. Returns... From this method True Will lead to with Statement suppresses the exception and continues execution immediately after with Statement after statement . otherwise , After this method is executed , The exception will continue to propagate . Exceptions that occur during the execution of this method replace with Any exception that occurs in the body of the statement . The passed in exception should not be explicitly re thrown , contrary , This method should return False To indicate that the method completed successfully and did not want to suppress the thrown exception . This allows context management code to easily detect __exit__() Whether the method actually failed .

      Typical uses of the context manager include saving and restoring various global states 、 Lock and unlock resources 、 Close open files, etc .

      When to use the context manager : When your code must open and close connections as part of its process ; When your code must use preconditions and postconditions (preconditions and post-conditions) when ; And when you try to manage limited resources on the system , Context manager is a good choice .

      The above content mainly refers to :

      1. https://docs.python.org/3/reference/datamodel.html#context-managers

      2. https://www.geeksforgeeks.org/context-manager-in-python/

      Here is the test code :

import contextlib
var = 3
if var == 1:
# reference: https://www.geeksforgeeks.org/context-manager-in-python/
# Class based context manager
class FileManager():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
# loading a file
with FileManager('test.txt', 'w') as f:
f.write('Test')
print(f.closed) # True
elif var == 2:
# https://medium.com/swlh/3-ways-to-create-context-managers-in-python-a88e3ba536f3
# Generator based context manager : Instead of __enter__ and __exit__ Method , Generators and @contextlib.contextmanager The decorator will be yield Run everything before the statement , As if it were __enter__ Part of the method
# It's the same , The resulting value may be __enter__ Method will return the result . after , Will run with What's in the block , As a last step , Will run yield Code after statement , As if it were __exit__ The method is the same
@contextlib.contextmanager
def file_hanlder(file_name, file_mode):
file = open(file_name, file_mode)
print("open file")
yield file # yeild The previous code will be used in the context manager as __enter__ Method execution , And pass the results yield return , All in yield The following code will be used as __exit__ Method execution
file.close()
print("close file")
with file_hanlder("test.txt", "w") as f:
f.write("Test2")
print("write file")
print(f.closed) # True
elif var == 3:
# https://medium.com/swlh/3-ways-to-create-context-managers-in-python-a88e3ba536f3
# Context manager based on function decorator : One of the problems with the function decorator method is the inability to access __enter__ Return value of method
class file_handler_mixin(contextlib.ContextDecorator):
def __init__(self, file_name, file_mode):
self._file_name = file_name
self._file_mode = file_mode
self._file = None
def __enter__(self):
print(f"Enter Method: File Name {self._file_name}")
self._file = open(self._file_name, self._file_mode) # Cannot access file object from decorator function
return self._file
def __exit__(self,exc_type,exc_value,exc_traceback):
print(f"Exit Method: File Mode {self._file_mode}")
self._file.close()
@file_handler_mixin("test.txt", "w")
def write_to_file():
print("Not access to the value returned by the __enter__ method")
write_to_file()
print("test finish")

      GitHubhttps://github.com/fengbingchun/Python_Test

版权声明
本文为[fengbingchun]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013180944105a.html

  1. L'application de Seed en python
  2. Python functional programming series 008: Testability
  3. [must see for getting started with Python] the difference and connection between cookie and session in Python!
  4. Python Xiaobai from scratch pyqt5 project actual combat (4) basic controls
  5. Python Xiaobai starts the pyqt5 project from scratch (3) connection between signal and slot
  6. Echarts ne peut pas afficher le HTML en PDF en utilisant le pdfkit de Python
  7. 一只Python 小white 的日常提问(づ ●─● )づ
  8. 2021 tutoriel complet d'automatisation des tests d'interface python [matériel d'apprentissage joint]
  9. Décrivez ce que les connaissances pertinentes jouent dans votre travail en utilisant arduino ou Python, y compris les bibliothèques pertinentes, en conjonction avec votre travail quotidien.
  10. Une question quotidienne d'un petit morceau de Python (づ● - ●)
  11. Python中字典问题请求解惑
  12. 一只Python 小white 的日常提問(づ ●─● )づ
  13. 在python中的问题,请问如何解决
  14. Only 10 questions are needed to easily master Matplotlib graphics processing | Python skill tree
  15. 在python中的問題,請問如何解决
  16. Comment résoudre le problème en python
  17. Demande de résolution de problèmes de dictionnaire en python
  18. 使用python,在一个命名为.txt文本文档写入n m乘法表。
  19. En utilisant Python, écrivez une table de multiplication n m dans un document texte nommé.txt.
  20. 使用python,在一個命名為.txt文本文檔寫入n m乘法錶。
  21. Python,前缀后缀相同时合并
  22. 关于#python#的问题:python
  23. 關於#python#的問題:python
  24. Python,前綴後綴相同時合並
  25. Questions sur # # Python #: Python
  26. Python, préfixe et suffixe combinés en même temps
  27. python manage.py shell无法运行,
  28. python manage.py shell無法運行,
  29. Le shell Python manage.py ne fonctionne pas,
  30. python中使用vscode Import 'matplotlib.pyplot' could not be resolved from source 问题
  31. [Chapter 11 of the full version] Python advanced crawler practice - system master Po anti climbing skills challenge high salary
  32. L'utilisation de vscode Import 'matplotlib.pyplot' en python ne peut pas être résolue à partir du problème source
  33. Python fusionne les deux listes et supprime les éléments dupliqués lors de la fusion
  34. [JS Reverse AES Reverse Encryption] python crawler combat, les jours sont de plus en plus décisifs
  35. 30 jeux Python. Je peux jouer à la pêche au travail pendant une journée.
  36. J'a i collecté un nouveau hit de liste en python, donc c'est un secret que quelqu'un d'autre peut devenir un magnat des médias!
  37. J'a i utilisé Python pour ramper à travers 5000 belles photos de papier peint, un jour oublié Premier amour!
  38. [Python planting system] the best green plant for your girlfriend. Girls love it when they see it! Attachment: should be able to feed - right??!
  39. [Python love guide] two small programs for sweetness burst table are released! Afraid you can't find someone?
  40. J'ai utilisé Python pour ramper 1000 lettres d'amour pour aider mon colocataire à exprimer les fleurs de classe, mais les inverser et les inverser... C'est le secret ultime des fleurs de classe!
  41. J'ai utilisé Python pour me connecter à la plus grande plate - forme de jeu au monde, et à quel point le cryptage steam est intelligent [code source inclus]
  42. python中列表转为矩阵后无法进行矩阵的乘法运算
  43. Python crawler Development and Learning full tutoriel 2nd Edition, banggan 100000 words [recommended Collection]
  44. Python crawler haut de gamme: microstore confus anti - décryptage
  45. La multiplication de la matrice ne peut pas être effectuée lorsque la liste est convertie en matrice en python
  46. Introduction to operators in python (Part 1)
  47. Are the dictionaries in Python ordered
  48. Introduction to dictionaries in Python
  49. List introduction in Python
  50. pandas比较两个dataframe特定数据列的数值是否相同并给出差值:使用np.where函数
  51. Python使用matplotlib绘制透明背景的可视化图像并保存透明背景的可视化结果(transparent background)
  52. Python self study notes -- basic grammar
  53. Python utilise matplotlib pour dessiner une image visuelle de l'arrière - plan transparent et enregistrer les résultats visuels de l'arrière - plan transparent
  54. Pandas compare les valeurs de deux colonnes de données spécifiques à dataframe et donne des valeurs de voyage: en utilisant la fonction np.where
  55. Comment configurer une application ASGI Django avec Postgres, nginx et uvicorn sur Ubuntu 20.04
  56. What are the advantages of Python and how to get started quickly
  57. Python self study notes -- basic data types
  58. Python code reading (Chapter 14): List Union
  59. Analyse statistique de la fonction de données des essais aléatoires Python
  60. Alien invasion project in Python application -- Aliens (Part 2)