contextmanager

__init__ vs __enter__ in context managers

╄→尐↘猪︶ㄣ 提交于 2020-12-29 02:41:49
问题 As far as I understand, __init__() and __enter__() methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between. What is the purpose of separating them into two methods, and what should I put into each? Edit: sorry, wasn't paying attention to the docs. Edit 2: actually, the reason I got confused is because I was thinking of @contextmanager decorator. A context manager created using @contextmananger can only be

How do I write a null (no-op) contextmanager in Python?

六月ゝ 毕业季﹏ 提交于 2020-11-30 04:39:08
问题 Sometimes I need a dummy context manager that does nothing. It can then be used as a stand-in for a more useful, but optional, context manager. For example: ctx_mgr = <meaningfulContextManager> if <condition> else <nullContextManager> with ctx_mgr: ... How do I define such a trivial, empty context manager? Does the Python library offer one off the shelf? How about cases where we want the context to be used with an as clause? with ctx_mgr as resource: <operations on resource> 回答1: Python 3.7

How do I write a null (no-op) contextmanager in Python?

做~自己de王妃 提交于 2020-11-30 04:36:06
问题 Sometimes I need a dummy context manager that does nothing. It can then be used as a stand-in for a more useful, but optional, context manager. For example: ctx_mgr = <meaningfulContextManager> if <condition> else <nullContextManager> with ctx_mgr: ... How do I define such a trivial, empty context manager? Does the Python library offer one off the shelf? How about cases where we want the context to be used with an as clause? with ctx_mgr as resource: <operations on resource> 回答1: Python 3.7

TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

杀马特。学长 韩版系。学妹 提交于 2020-06-27 14:40:09
问题 I am trying to open, read, modify, and close a json file using the example here: How to add a key-value to JSON data retrieved from a file with Python? import os import json path = '/m/shared/Suyash/testdata/BIDS/sub-165/ses-1a/func' os.chdir(path) string_filename = "sub-165_ses-1a_task-cue_run-02_bold.json" with open ("sub-165_ses-1a_task-cue_run-02_bold.json", "r") as jsonFile: json_decoded = json.load(jsonFile) json_decoded["TaskName"] = "CUEEEE" with open(jsonFile, 'w') as jsonFIle: json

How to properly annotate a ContextManager in PyCharm?

本秂侑毒 提交于 2020-06-23 06:44:25
问题 How can I annotate the yield type of a contextmanager in PyCharm so that it properly guesses the type of the value used in the with clauses - just as it guesses that the f created in with open(...) as f is a file? For example, I have a context manager like this: @contextlib.contextmanager def temp_borders_file(geometry: GEOSGeometry, name='borders.json'): with TemporaryDirectory() as temp_dir: borders_file = Path(dir) / name with borders_file.open('w+') as f: f.write(geometry.json) yield

Python: standard function and context manager?

不想你离开。 提交于 2020-05-10 07:39:06
问题 In python, there are many functions that work as both standard functions and context managers. For example open() can be called either as: my_file=open(filename,'w') or with open(filename,'w') as my_file: Both giving you a my_file object that can be used to do whatever you need to. In general the later is preferable, but there are times when one might want to do the former as well. I've been able to figure out how to write a context manager, either by creating a class with __enter__ and _

py.test - how to use a context manager in a funcarg/fixture

一曲冷凌霜 提交于 2020-02-03 04:26:09
问题 Closely related: In python, is there a good idiom for using context managers in setup/teardown I have a context manager that is used in tests to fix the time/timezone. I want to have it in a pytest funcarg (or fixture, we are using pytest 2.2.3 but I can translate backwards). I could just do this: def pytest_funcarg__fixedTimezone(request): # fix timezone to match Qld, no DST to worry about and matches all # Eastern states in winter. fixedTime = offsetTime.DisplacedRealTime(tz=' Australia

Python timeout context manager with threads

江枫思渺然 提交于 2020-01-12 07:15:34
问题 I have timeout context manager that works perfectly with signals but it raises error in multithread mode because signals work only in main thread. def timeout_handler(signum, frame): raise TimeoutException() @contextmanager def timeout(seconds): old_handler = signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0) signal.signal(signal.SIGALRM, old_handler) I've seen decorator implementation of timeout but I don't know how to pass yield inside

Why does my contextmanager-function not work like my contextmanager class in python?

我与影子孤独终老i 提交于 2020-01-11 06:09:11
问题 In my code, I need to be able to open and close a device properly, and therefore see the need to use a context manager. While a context manager is usually defined as a class with __enter__ and __exit__ methods, there also seem to be the possibility to decorate a function for use with the context manager (see a recent post and another nice example here). In the following (working) code snippet, I have implemented the two possibilities; one just need to swap the commented line with the other

what does yield without value do in context manager

不问归期 提交于 2020-01-01 04:13:27
问题 import contextlib import time @contextlib.contextmanager def time_print(task_name): t = time.time() try: yield finally: print task_name, "took", time.time() - t, "seconds." def doproc(): x=1+1 with time_print("processes"): [doproc() for _ in range(500)] # processes took 15.236166954 seconds. when does doproc get executed when using this decorator? 回答1: yield expression returns control to the whatever is using the generator. The generator pauses at this point, which means that the