简体   繁体   中英

Python iterable and context manager

I want behaviour as such:

with A() as f:
    for x in f:
        do_something(f)

is this the right way to do it?

class A:
    def __enter__(self):
        print "Entering context"

    def __iter__(self):
        for x in ["some","list"]:
            yield x

    def __exit__(self):
        print "Deleting context"

Your contextmanager.__enter__ method needs to return the iterable. It can be self :

def __enter__(self):
    print "Entering context"
    return self

See the With Statement Context Managers documentation :

object.__enter__(self)

Enter the runtime context related to this object. The with statement will bind this method's return value to the target(s) specified in the as clause of the statement, if any.

so whatever the method returns is then bound to the name given as the as target.

Your contextmanager.__exit__ method needs to be able to accept the exception if one was raised:

def __exit__(self, exc_type, exc_value, traceback):

When there is no exception, the with statement gives you three None arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM