Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?
like image 498
Kam Avatar asked Apr 26 '14 16:04

Kam


People also ask

What does with AS do in Python?

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.

What is the use of with statement?

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.

What is open and with statement in Python?

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.

When we use with clause to open a file the advantage is?

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.


1 Answers

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.

like image 133
Lev Levitsky Avatar answered Oct 20 '22 10:10

Lev Levitsky