Python

contextlib

contextlib.contextmanager

  • 用途:上下文实现装饰器

    • 实现try...finally...语句的生成器上下文管理器语法
    • try部分:生成器部分,with语句进入时执行
    • finally部分:清理部分,with语句退出时执行
  • 用法

    • 定义

      1
      2
      3
      4
      5
      6
      7
      @contextmanager
      def some_generator(<parameters>):
      <setup>
      try:
      yield <value>
      finally:
      <cleanup>
    • 用法

      1
      2
      with some_generator(<argrument>) as <variable>:
      <body>
    • 等价于

      1
      2
      3
      4
      5
      6
      <setup>
      try:
      <variable> = <value>
      <body>
      finally:
      <cleanup>
Author

UBeaRLy

Posted on

2019-03-30

Updated on

2019-03-30

Licensed under

Comments