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:
print(derived)
return a None
object and not a Derived
object?In Python, the with statement replaces a try-catch block with a concise shorthand. More importantly, it ensures closing resources right after processing them. A common example of using the with statement is reading or writing to a file. A function or class that supports the with statement is known as a context manager.
Thus, with statement helps avoiding bugs and leaks by ensuring that a resource is properly released when the code using the resource is completely executed. The with statement is popularly used with file streams, as shown above and with Locks, sockets, subprocesses and telnets etc.
In Python you need to give access to a file by opening it. You can do it by using the open() function. Open returns a file object, which has methods and attributes for getting information about and manipulating the opened file.
Using with means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need.
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 theas
clause of the statement, if any.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With