Previous post
I wish I had used contextmanager
from the beginning without the difficulty of decorating ...
yo.py
from contextlib import contextmanager
import random
class Prot:
def __init__(self):
pass
@contextmanager
def yoyo(self, hey):
print('gacha.') # __enter__
yield hey # as
print('Everything Done Right.') # __exit__
def yo_gacha(self, y):
yo = [y*i for i in range(10)]
return yo[random.randint(0, 9)]
if __name__ == '__main__':
p = Prot()
with p.yoyo('hey') as y:
print(p.yo_gacha(y))
contextlib.contextmanager
is a decorator that applies with
to a good feeling and divides it into __enter__
and __exit__
with yield
in between.
One indent is sacrificed, but the description is easy and very easy to understand
It is easy to understand that if you pass it with yield
, you can receive it with ʻas`.
It may be better to use a decorator when I want to wrap various things, but I learned
Recommended Posts