Python Decorator: Contextlib

Source: Internet
Author: User
Tags python decorator

Context:

Start information

|

Intermediate output Information

|

End Message


Contextual Environment 1:

#!/usr/bin/python# -*- coding: utf-8 -*-class query (object):     Def __init__ (self, name):         self.name = name     def __enter__ (self):         print (' Begin ' )         return self    def __exit__ ( Self, exc_type, exc_value, traceback):        if  Exc_type:            print (' Error ')          else:             print (' End ')     def query (self):         print (' query info about %s ... '  % self.name)          with query(' Bob ')  as q:    q.query ()         query ( ' Bob '). Query ()

run Result:

Beginquery info about Bob ... Endquery info about Bob ...


Context 2: @contextmanager

From contextlib import contextmanagerclass query (object):    def  __init__ (Self, name):        self.name = name     def query (self):         print (' Query info  about %s '  % self.name) @contextmanagerdef  create_query (name):     print (' Begin ')     q = query (name)     yield q     print (' End ')     with create_query (' Bob ')  as q:     q.query ()

Operation Result:

Beginquery info about Bob ... End


Context 3: @contextmanager simplify again

From contextlib import contextmanager@contextmanagerdef tag (name): Print ("<%s>"% name) yield print ("</% S> "% name" with tag ("H1"): Print ("Hello") Print ("World")

The result of the above code execution is:


No context: @closing use closing () to turn the object into a context object, for example, using Urlopen () with a with statement:

from contextlib import closingfrom urllib.request import urlopenwith  Closing (Urlopen (' https://www.baidu.com '))  as page:    for line in  page:        print (line) 

B ' 


Don't know how to verify the closing

from contextlib import contextmanager@contextmanagerdef closing (thing):     try:        yield thing    finally:         thing.close () 

The result of the above code execution is:



Python Decorator: Contextlib

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.