7. The 'with' and 'as' Keywords (little off-topic)


#1

From lesson:

You may not know this, but file objects contain a special pair of built-in methods: enter() and exit(). The details aren't important...

In builtins.py:

    def __enter__(self, *args, **kwargs): # real signature unknown
        pass

    def __exit__(self, *args, **kwargs): # real signature unknown
        pass

It's because this functions declared on C?


#2

Lol.

#python 3.x
from io import BufferedIOBase

file = open("test.txt", "w")


class MyFile(file.__class__):
    def __enter__(self, *args, **kwargs):
        print("WITH")
        return super().__enter__(*args, **kwargs)

    def __exit__(self, *args, **kwargs):
        print("AS")
        return super().__exit__(*args, **kwargs)

with MyFile(BufferedIOBase(file)) as power:
    pass

file.close()

Out:

WITH
AS


#3

That's still entirely python

Classes may implement particular names to define behavior that has special significance to python. For example opening and closing a resource as you did here, or iterating, or initiating (__init__)

You can read more about them at
https://docs.python.org/3/reference/datamodel.html
or
https://docs.python.org/2/reference/datamodel.html


#4

Thanks Jonatan, it's really helpful!


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.