contextmanager

Context Manager that handles exceptions

你。 提交于 2021-02-11 15:25:16
问题 I am trying to wrap my head around how to write a context manager that deals with writing some logs while handling any exceptions. The problem I am trying to solve is to make code like this: try: # code that can raise exception here except Exception as e: print('failed', e) print('all good') This is a repeated pattern I have in the code and I think it's best handled with a context manager like: with my_ctx_manager(success_msg='all good', failed_msg='failed): # code that can raise exception

Writing a contextmanager that patches an object

。_饼干妹妹 提交于 2021-02-10 17:47:58
问题 In my Python 3 test code, I have a lot of these statements: from unittest.mock import patch user = User(...) with patch.object(MyAuthenticationClass, 'authenticate', return_value=(user, 'token'): # do something Now I want to write this as: with request_user(user): # do something How would I write a method request_user as context manager such that it patches the authentication in this way, and removes the patch after the with block? 回答1: You can write a simple wrapper like this: def request

Python: Why am I receiving an AttributeError: __enter__

独自空忆成欢 提交于 2021-02-10 05:14:32
问题 I am not reassigning the open keyword yet still receive this error. Any suggestions or direction to fix my error? with tempfile.mkdtemp() as test_dir: print(test_dir) AttributeError: __enter__ I am also new to python and I am having a hard time understanding these concepts. 回答1: You're using mkdtemp incorrectly. mkdtemp returns the path name as str, not a context manager. If you want a context manager for managing a temporary directory, you need to use TemporaryDirectory, which is available

Why can you use open() as context manager?

☆樱花仙子☆ 提交于 2021-02-07 10:54:43
问题 From Python's source code of open, I think open is just a normal function. Why can we use it like below? with open('what_are_context_managers.txt', 'r') as infile: for line in infile: print('> {}'.format(line)) Since is neither implements __enter__ nor __exit__ , nor uses contextlib.contextmanager decorator. 回答1: You are not using the open function as a context manager. It is the result of the open(...) call expression that is the context manager. open() returns a file object, and it is that

manually open context manager

十年热恋 提交于 2021-02-04 18:48:09
问题 My question is, how can I execute any context manager without using with ? Python has the idea of context managers, instead of file = open('some_file', 'w') try: file.write('Hola!') finally: file.close() # end try you can write with open('some_file', 'w') as opened_file: opened_file.write('Hola!') # end with While in most cases the second one is the golden solution, for testing and exploring in the interactive console, the first one can be much better used, as you can write it line by line. >

Generator and context manager at the same time

两盒软妹~` 提交于 2021-01-29 07:01:32
问题 Imagine I have some code that I want it to run: with F() as o: while True: a = o.send(2) print(a) It means that the F class should return an generator and also it is context manager , generally I want a context manager to be generator too. I tried this: class F: def __enter__(self): return self def __exit__(self, *exc): print('exit') def __next__(self): return 5 def __iter__(self): return self As expected this will return AttributeError: 'F' object has no attribute 'send' , I handled this

Generator and context manager at the same time

喜你入骨 提交于 2021-01-29 06:57:56
问题 Imagine I have some code that I want it to run: with F() as o: while True: a = o.send(2) print(a) It means that the F class should return an generator and also it is context manager , generally I want a context manager to be generator too. I tried this: class F: def __enter__(self): return self def __exit__(self, *exc): print('exit') def __next__(self): return 5 def __iter__(self): return self As expected this will return AttributeError: 'F' object has no attribute 'send' , I handled this

Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

爱⌒轻易说出口 提交于 2021-01-20 17:18:28
问题 I have searched and I'm unable to come up with any good reason to use python's __enter__ / __exit__ rather than __init__ (or __new__ ?) / __del__ . I understand that __enter__ / __exit__ are intended for use with the with statement as context managers, and the with statement is great. But the counterpart to that is that any code in those blocks is only executed in that context. By using these instead of __init__ / __del__ I appear to be creating an implicit contract with callers that they

Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

走远了吗. 提交于 2021-01-20 17:18:07
问题 I have searched and I'm unable to come up with any good reason to use python's __enter__ / __exit__ rather than __init__ (or __new__ ?) / __del__ . I understand that __enter__ / __exit__ are intended for use with the with statement as context managers, and the with statement is great. But the counterpart to that is that any code in those blocks is only executed in that context. By using these instead of __init__ / __del__ I appear to be creating an implicit contract with callers that they

Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

时间秒杀一切 提交于 2021-01-20 17:18:07
问题 I have searched and I'm unable to come up with any good reason to use python's __enter__ / __exit__ rather than __init__ (or __new__ ?) / __del__ . I understand that __enter__ / __exit__ are intended for use with the with statement as context managers, and the with statement is great. But the counterpart to that is that any code in those blocks is only executed in that context. By using these instead of __init__ / __del__ I appear to be creating an implicit contract with callers that they