Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do the three arguments come from in this __exit__ function extending a python base type?

I tried to play around with the built in string type, wondering if I could use strings with the with syntax. Obviously the following will fail:

with "hello" as hello:
    print(f"{hello} world!")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __enter__

Then, just deriving a class from str with the two needed attributes for with:

class String(str):
    def __enter__(self):
        return self
    def __exit__(self):
        ...

with String("hello") as hello:
    print(f"{hello} world!")

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: __exit__() takes 1 positional argument but 4 were given

Ok, I wonder what those arguments are.., I added *args, **kwargs to __exit__, and then tried it again:

class String(str):
    def __enter__(self):
        return self
    def __exit__(self, *args, **kwargs):
        print("args: ", args)
        print("kwargs: ", kwargs)

with String("hello") as hello:
    print(f"{hello} world!")

hello world!
args:  (None, None, None)
kwargs:  {}

Works with different types too that I guess can be normally called with str(), but what are those three arguments? How do I go about finding more information on what the three extra arguments were? I guess finally, where can I go to see the implementation of built-in types, etc...?

like image 963
jupiar Avatar asked Aug 17 '26 07:08

jupiar


1 Answers

These are actually methods(__enter__() & __exit__()) of contextmanager class. Please refer to this link for detailed explaination.

The __exit__() method will exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed

Those three arguments are:

  1. exception_type
  2. exception_value
  3. traceback

The values of these arguments contain information regarding the thrown exception. If the values equal to None means no exception was thrown.

like image 137
shaswat.dharaiya Avatar answered Aug 19 '26 15:08

shaswat.dharaiya