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...?
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:
The values of these arguments contain information regarding the thrown exception. If the values equal to None means no exception was thrown.
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