Python com… como no gerenciador de contexto personalizado
Eu escrevi um gerenciador de contexto simples em Python para lidar com testes de unidade (e para tentar aprender gerenciadores de contexto):
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test_count += 1
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, exc_traceback):
if exc_value == None:
print 'Test %d passed' %self.test_number
else:
print 'Test %d failed: %s' %(self.test_number, exc_value)
return True
Se eu escrever um teste da seguinte forma, tudo funcionará bem.
test = TestContext()
with test:
print 'running test %d....' %test.test_number
raise Exception('this test failed')
No entanto, se eu tentar usar com ... como, não recebo uma referência ao objeto TestContext (). Executando isso:
with TestContext() as t:
print t.test_number
Gera a exceção'NoneType' object has no attribute 'test_number'
.
Onde eu estou errando?