I'm trying to understand the workings of Python's gerenciadores de contexto
, implementing one based on contextmanager
. Here is the script:
class contextmanager(object):
def __init__(self, func):
self._func = func
def __call__(self, *args, **kwargs):
print('__call__')
self._gen = self._func(*args, **kwargs)
return self.__enter__()
def __enter__(self):
print('__enter__')
return next(self._gen)
def __exit__(self, exc_type, exc_value, exc_tb):
print('__exit__')
next(self._gen)
import os
@contextmanager
def changepath(path):
actual = os.getcwd()
os.chdir(path)
yield
os.chdir(actual)
with changepath('downloads') as path:
print(os.getcwd())
print(os.getcwd())
But the output is:
__call__
__enter__
Traceback (most recent call last):
File "C:\Users\Thiaguinho\AppData\Local\Programs\Python\Python36-32\Code\NIGHT\_eigth_asyncio.py", line 99, in <module>
with changepath('downloads') as path:
AttributeError: __enter__
Can anyone tell me where the error is?