yayu
yayu

Reputation: 8098

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"

Upvotes: 1

Views: 3806

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123750

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.

Upvotes: 7

Related Questions