Python之contextlib库及源码分析建议收藏

AbstractContextManager(abc.ABC)上下文管理抽象类,子类必须实现__enter__(self)、__exit__(self)ContextDecorator(objec

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

Python之contextlib库及源码分析建议收藏此处内容已经被作者隐藏,请输入验证码查看内容
验证码:
请关注本站微信公众号,回复“”,获取验证码。在微信里搜索“”或者“”或者微信扫描右侧二维码都可以关注本站微信公众号。

Utilities for
with-statement contexts

  __all__ = [“contextmanager”, “closing”, “AbstractContextManager”,

               ”ContextDecorator”, “ExitStack”, “redirect_stdout”,

               ”redirect_stderr”, “suppress”]

AbstractContextManager(abc.ABC)

  上下文管理抽象类,子类必须实现__enter__(self)、__exit__(self)

class AbstractContextManager(abc.ABC):

    """An abstract base class for context managers."""

    def __enter__(self):
        """Return `self` upon entering the runtime context."""
        return self

    @abc.abstractmethod
    def __exit__(self, exc_type, exc_value, traceback):
        """Raise any exception triggered within the runtime context."""
        return None

    @classmethod
    def __subclasshook__(cls, C):
        if cls is AbstractContextManager:
            if (any("__enter__" in B.__dict__ for B in C.__mro__) and
                any("__exit__" in B.__dict__ for B in C.__mro__)):
                return True
        return NotImplemented

ContextDecorator(object)

  上下文管理基类或mixin类,该类可以像装饰器一样工作,提供你需要实现的任何辅助功能

class ContextDecorator(object):
    "A base class or mixin that enables context managers to work as decorators."

    def _recreate_cm(self):
        """Return a recreated instance of self.

        Allows an otherwise one-shot context manager like
        _GeneratorContextManager to support use as
        a decorator via implicit recreation.

        This is a private interface just for _GeneratorContextManager.
        See issue #11647 for details.
        """
        return self

    def __call__(self, func):
        @wraps(func)
        def inner(*args, **kwds):
            with self._recreate_cm():
                return func(*args, **kwds)
        return inner

_GeneratorContextManager(ContextDecorator, AbstractContextManager)

  contextmanager装饰器的包装函数提供以下方法:

  _recreate_cm(重新生成新对像),self.__class__(*args, **kwds)

  __enter__上下文管理进入函数

  __exit__上下文管理退出函数

  可以根据ContextDecorator实现任何想实现的辅助功能

class _GeneratorContextManager(ContextDecorator, AbstractContextManager):
    """Helper for @contextmanager decorator."""

    def __init__(self, func, args, kwds):
        self.gen = func(*args, **kwds)
        logger.info("get generator by with:{}".format(self.gen))
        self.func, self.args, self.kwds = func, args, kwds
        # Issue 19330: ensure context manager instances have good docstrings
        doc = getattr(func, "__doc__", None)  #得到函数文档,第三个参数为默认参数
        logger.info("doc:{}".format(doc))
        if doc is None:
            doc = type(self).__doc__
        self.__doc__ = doc
        # Unfortunately, this still doesn't provide good help output when
        # inspecting the created context manager instances, since pydoc
        # currently bypasses the instance docstring and shows the docstring
        # for the class instead.
        # See http://bugs.python.org/issue19404 for more details.

    def _recreate_cm(self):
        # _GCM instances are one-shot context managers, so the
        # CM must be recreated each time a decorated function is
        # called
        return self.__class__(self.func, self.args, self.kwds)

    def __enter__(self):
        logger.info("__enter__:you can add you method")
        
        @ContextDecorator()
        def testfun(*args, **kwds):
            logger.info("@ContextDecorator():testfun test success")   
        testfun("hello")
        
        try:
            return next(self.gen)
        except StopIteration:
            raise RuntimeError("generator didn't yield") from None

    def __exit__(self, type, value, traceback):
        logger.info("__exit__")
        logger.info("type:{}".format(type))
        if type is None:
            try:
                next(self.gen)
            except StopIteration:
                return
            else:
                raise RuntimeError("generator didn't stop")
        else:
            if value is None:
                # Need to force instantiation so we can reliably
                # tell if we get the same exception back
                value = type()
            try:
                self.gen.throw(type, value, traceback)
                raise RuntimeError("generator didn't stop after throw()")
            except StopIteration as exc:
                # Suppress StopIteration *unless* it's the same exception that
                # was passed to throw().  This prevents a StopIteration
                # raised inside the "with" statement from being suppressed.
                return exc is not value
            except RuntimeError as exc:
                # Don't re-raise the passed in exception. (issue27112)
                if exc is value:
                    return False
                # Likewise, avoid suppressing if a StopIteration exception
                # was passed to throw() and later wrapped into a RuntimeError
                # (see PEP 479).
                if exc.__cause__ is value:
                    return False
                raise
            except:
                # only re-raise if it's *not* the exception that was
                # passed to throw(), because __exit__() must not raise
                # an exception unless __exit__() itself failed.  But throw()
                # has to raise the exception to signal propagation, so this
                # fixes the impedance mismatch between the throw() protocol
                # and the __exit__() protocol.
                #
                if sys.exc_info()[1] is not value:
                    raise

装饰器contextmanager

def contextmanager(func):
    """@contextmanager decorator.

    Typical usage:

        @contextmanager
        def some_generator(<arguments>):
            <setup>
            try:
                yield <value>
            finally:
                <cleanup>

    This makes this:

        with some_generator(<arguments>) as <variable>:
            <body>

    equivalent to this:

        <setup>
        try:
            <variable> = <value>
            <body>
        finally:
            <cleanup>

    """
    @wraps(func)
    def helper(*args, **kwds):
        return _GeneratorContextManager(func, args, kwds)
    return helper

用例:

Python之contextlib库及源码分析建议收藏
Python之contextlib库及源码分析建议收藏

#coding = utf-8

import abc
from functools import wraps

import logging
logging.basicConfig(level=logging.INFO, filename="logging.txt", filemode="w+", \
                format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class AbstractContextManager(abc.ABC):

    """An abstract base class for context managers."""

    def __enter__(self):
        """Return `self` upon entering the runtime context."""
        return self

    @abc.abstractmethod
    def __exit__(self, exc_type, exc_value, traceback):
        """Raise any exception triggered within the runtime context."""
        return None

    @classmethod
    def __subclasshook__(cls, C):
        if cls is AbstractContextManager:
            if (any("__enter__" in B.__dict__ for B in C.__mro__) and
                any("__exit__" in B.__dict__ for B in C.__mro__)):
                return True
        return NotImplemented


class ContextDecorator(object):
    "A base class or mixin that enables context managers to work as decorators."

    def _recreate_cm(self):
        """Return a recreated instance of self.

        Allows an otherwise one-shot context manager like
        _GeneratorContextManager to support use as
        a decorator via implicit recreation.

        This is a private interface just for _GeneratorContextManager.
        See issue #11647 for details.
        """
        return self

    def __call__(self, func):
        #logger.info("ContextDecorator func:{}".format(func))
        @wraps(func)
        def inner(*args, **kwds):
            #with self._recreate_cm():
            logger.info("you can do something in decorator")
            return func(*args, **kwds)
        return inner


class _GeneratorContextManager(ContextDecorator, AbstractContextManager):
    """Helper for @contextmanager decorator."""

    def __init__(self, func, args, kwds):
        self.gen = func(*args, **kwds)
        logger.info("get generator by with:{}".format(self.gen))
        self.func, self.args, self.kwds = func, args, kwds
        # Issue 19330: ensure context manager instances have good docstrings
        doc = getattr(func, "__doc__", None)  #得到函数文档,第三个参数为默认参数
        logger.info("doc:{}".format(doc))
        if doc is None:
            doc = type(self).__doc__
        self.__doc__ = doc
        # Unfortunately, this still doesn't provide good help output when
        # inspecting the created context manager instances, since pydoc
        # currently bypasses the instance docstring and shows the docstring
        # for the class instead.
        # See http://bugs.python.org/issue19404 for more details.

    def _recreate_cm(self):
        # _GCM instances are one-shot context managers, so the
        # CM must be recreated each time a decorated function is
        # called
        return self.__class__(self.func, self.args, self.kwds)

    def __enter__(self):
        logger.info("__enter__:you can add you method")
        
        @ContextDecorator()
        def testfun(*args, **kwds):
            logger.info("@ContextDecorator():testfun test success")   
        testfun("hello")
        
        try:
            return next(self.gen)
        except StopIteration:
            raise RuntimeError("generator didn't yield") from None

    def __exit__(self, type, value, traceback):
        logger.info("__exit__")
        logger.info("type:{}".format(type))
        if type is None:
            try:
                next(self.gen)
            except StopIteration:
                return
            else:
                raise RuntimeError("generator didn't stop")
        else:
            if value is None:
                # Need to force instantiation so we can reliably
                # tell if we get the same exception back
                value = type()
            try:
                self.gen.throw(type, value, traceback)
                raise RuntimeError("generator didn't stop after throw()")
            except StopIteration as exc:
                # Suppress StopIteration *unless* it's the same exception that
                # was passed to throw().  This prevents a StopIteration
                # raised inside the "with" statement from being suppressed.
                return exc is not value
            except RuntimeError as exc:
                # Don't re-raise the passed in exception. (issue27112)
                if exc is value:
                    return False
                # Likewise, avoid suppressing if a StopIteration exception
                # was passed to throw() and later wrapped into a RuntimeError
                # (see PEP 479).
                if exc.__cause__ is value:
                    return False
                raise
            except:
                # only re-raise if it's *not* the exception that was
                # passed to throw(), because __exit__() must not raise
                # an exception unless __exit__() itself failed.  But throw()
                # has to raise the exception to signal propagation, so this
                # fixes the impedance mismatch between the throw() protocol
                # and the __exit__() protocol.
                #
                if sys.exc_info()[1] is not value:
                    raise

def contextmanager(func):
    """@contextmanager decorator.

    Typical usage:

        @contextmanager
        def some_generator(<arguments>):
            <setup>
            try:
                yield <value>
            finally:
                <cleanup>

    This makes this:

        with some_generator(<arguments>) as <variable>:
            <body>

    equivalent to this:

        <setup>
        try:
            <variable> = <value>
            <body>
        finally:
            <cleanup>

    """
    @wraps(func)
    def helper(*args, **kwds):
        return _GeneratorContextManager(func, args, kwds)
    return helper
 
@contextmanager
def file_open(path):
    ''' file open test'''
    try:
        f_obj = open(path,"w")
        yield f_obj
    except OSError:
        print("We had an error!")
    finally:
        print("Closing file")
        f_obj.close()

if __name__ == "__main__": 
    with file_open("contextlibtest.txt") as fobj:
        fobj.write("Testing context managers")
        logger.info("write file success")

View Code

关键输出:

2018-03-22 15:36:43,249 - __main__ - INFO - get generator by with:<generator object file_open at 0x01DE4870>
2018-03-22 15:36:43,249 - __main__ - INFO - doc: file open test
2018-03-22 15:36:43,249 - __main__ - INFO - __enter__:you can add you method
2018-03-22 15:36:43,249 - __main__ - INFO - you can do something in decorator
2018-03-22 15:36:43,249 - __main__ - INFO - @ContextDecorator():testfun test success
2018-03-22 15:36:43,249 - __main__ - INFO - write file success
2018-03-22 15:36:43,249 - __main__ - INFO - __exit__
2018-03-22 15:36:43,249 - __main__ - INFO - type:None

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/120185.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 谁有FlashFXP可用注册码

    谁有FlashFXP可用注册码 急用,谢了

  • matlab求解不定方程组_matlab解参数方程组

    matlab求解不定方程组_matlab解参数方程组最想说的一句话:要查matlab用法,一定要到官网去查,一些用法matlab官方是在不断更新的,现存的一些办法已经无法解决问题使用的是solve这个函数它拥有解决优化问题,解方程的功能,下面我将举一些常用的例子文章目录一、解单变量方程二、解多变量方程三、解带参数方程四、解不等式知识点总结一、解单变量方程题目:求解方程2x+1=0 2x+1=02x+1=0symsx…

  • sql中的declare_如何声明变量

    sql中的declare_如何声明变量在sql语句中添加变量。declare @local_variabledata_type声明时需要指定变量的类型,可以使用set和select对变量进行赋值,在sql语句中就可以使用@local_variable来调用变量 声明中可以提供值,否则声明之后所有变量将初始化为NULL。 例如:declare@idint

  • 培训师电梯销售法则-三句半「建议收藏」

    培训师电梯销售法则-三句半「建议收藏」今天在北京一个神奇的培训中心开发一门无线接入技术的培训课件,开发完毕以后,进行了课程试讲,总体试讲的情况还是很不错的,但是在总结阶段,效果并不理想,因此辅导老师最后给出了一个电梯销售法则-三句半,下面首先介绍一下电梯销售法则: “麦肯锡30秒电梯理论”来源于麦肯锡公司一次沉痛的教训。  麦肯锡公司曾经得到过一次沉痛的教训:该公司曾经为一家重要的大客户做咨询。咨询结束…

  • Java入门——第一个Java程序HelloWorld(Dos命令窗口)

    Java入门——第一个Java程序HelloWorld(Dos命令窗口)麻烦找一个指定盘符的确切文件位置(尽量不要把要运行的.java文件建在桌面上,因为在Dos命令行中找文件路径比较麻烦!),可以创建一个专门用来练习入门Java程序的文件夹。(比如我这个暂时存放.java文件的文件夹在F盘的Java_WorkBenth文件夹里面)1、第一步,打开Windows资源管理器的查看文件后缀名功能(防止出现xxx.java.txt的文件格式)。2、创建一…

  • 软件测试(3) UFT12使用_GUITest

    软件测试(3) UFT12使用_GUITest环境:UFT12,Win10,VS2015&VS2017启动UFT12,为了启动方便修改快捷方式。设置插件,WPF相关的都设置起来。新建项目点击录制按钮(F6),设置启动程序。确定,开始录制。程序启动,显示登录界面。操作:切换IP,点击按钮,登录。点击工具栏按钮,停止录制。点击运行按钮(F5)。

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号