3

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...?

alexexchanges
  • 3,252
  • 4
  • 17
  • 38
  • 1
    Check out this question: https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit – Simon Crane Sep 27 '19 at 09:40
  • 1
    https://docs.quantifiedcode.com/python-anti-patterns/correctness/exit_must_accept_three_arguments.html – user2390182 Sep 27 '19 at 09:40
  • Ah I see, the link @schwobaseggl suggested was quite useful, aSimon Crane also. Makes complete sense now what those three arguments are! Thanks! – alexexchanges Sep 27 '19 at 09:48

1 Answers1

2

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.

shaswat.dharaiya
  • 381
  • 4
  • 13