1. contextlib
    2. 阅读: 31618
    3. Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们。正确关闭文件资源的一个方法是使用try...finally
    4. try:
    5. f = open('/path/to/file', 'r')
    6. f.read()
    7. finally:
    8. if f:
    9. f.close()
    10. try...finally非常繁琐。Pythonwith语句允许我们非常方便地使用资源,而不必担心资源没有关闭,所以上面的代码可以简化为:
    11. with open('/path/to/file', 'r') as f:
    12. f.read()
    13. 并不是只有open()函数返回的fp对象才能使用with语句。实际上,任何对象,只要正确实现了上下文管理,就可以用于with语句。
    14. 实现上下文管理是通过__enter____exit__这两个方法实现的。例如,下面的class实现了这两个方法:
    15. class Query(object):
    16. def __init__(self, name):
    17. self.name = name
    18. def __enter__(self):
    19. print('Begin')
    20. return self
    21. def __exit__(self, exc_type, exc_value, traceback):
    22. if exc_type:
    23. print('Error')
    24. else:
    25. print('End')
    26. def query(self):
    27. print('Query info about %s...' % self.name)
    28. 这样我们就可以把自己写的资源对象用于with语句:
    29. with Query('Bob') as q:
    30. q.query()
    31. @contextmanager
    32. 编写__enter____exit__仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下:
    33. from contextlib import contextmanager
    34. class Query(object):
    35. def __init__(self, name):
    36. self.name = name
    37. def query(self):
    38. print('Query info about %s...' % self.name)
    39. @contextmanager
    40. def create_query(name):
    41. print('Begin')
    42. q = Query(name)
    43. yield q
    44. print('End')
    45. @contextmanager这个decorator接受一个generator,用yield语句把with ... as var把变量输出出去,然后,with语句就可以正常地工作了:
    46. with create_query('Bob') as q:
    47. q.query()
    48. 很多时候,我们希望在某段代码执行前后自动执行特定代码,也可以用@contextmanager实现。例如:
    49. @contextmanager
    50. def tag(name):
    51. print("<%s>" % name)
    52. yield
    53. print("</%s>" % name)
    54. with tag("h1"):
    55. print("hello")
    56. print("world")
    57. 上述代码执行结果为:
    58. <h1>
    59. hello
    60. world
    61. </h1>
    62. 代码的执行顺序是:
    63. with语句首先执行yield之前的语句,因此打印出<h1>;
    64. yield调用会执行with语句内部的所有语句,因此打印出helloworld
    65. 最后执行yield之后的语句,打印出</h1>。
    66. 因此,@contextmanager让我们通过编写generator来简化上下文管理。
    67. @closing
    68. 如果一个对象没有实现上下文,我们就不能把它用于with语句。这个时候,可以用closing()来把该对象变为上下文对象。例如,用with语句使用urlopen():
    69. from contextlib import closing
    70. from urllib.request import urlopen
    71. with closing(urlopen('https://www.python.org')) as page:
    72. for line in page:
    73. print(line)
    74. closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单:
    75. @contextmanager
    76. def closing(thing):
    77. try:
    78. yield thing
    79. finally:
    80. thing.close()
    81. 它的作用就是把任意对象变为上下文对象,并支持with语句。
    82. @contextlib还有一些其他decorator,便于我们编写更简洁的代码。