16

I am trying to learn python and I landed on the

with..as

construct, that used like this:

with open("somefile.txt", 'rt') as file:
    print(file.read()) 
    # at the end of execution file.close() is called automatically.

So as a learning strategy I tried to do the following:

class Derived():

    def __enter__(self):
        print('__enter__')

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

with  Derived() as derived:
    print(derived)

and I got this output:

__enter__
None
__exit__

My question is then:

  • why did print(derived) return a None object and not a Derived object?
1
  • 2
    __enter__ must return the object that is bound to dervied.
    – Daniel
    Apr 26, 2014 at 16:22

1 Answer 1

17

The name derived is bound to the object returned by the __enter__ method, which is None. Try:

def __enter__(self):
    print('__enter__')
    return self

Docs:

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.

2
  • I looked everywhere I wasn't able to read this anywhere? How could I have figured it out? is there a manual explaining this requirement anywhere?
    – Kam
    Apr 26, 2014 at 16:23
  • 2
    @Kam Updated with the doc reference Apr 26, 2014 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.