Trying to figure out how the 'with..as' construct works in python

python

Solution

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.

Problem

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?

Original source