contextmanager

Asynchronous context manager

瘦欲@ 提交于 2019-12-30 00:14:13
问题 I have an asynchronous API which I'm using to connect and send mail to an SMTP server which has some setup and tear down to it. So it fits nicely into using a contextmanager from Python 3's contextlib . Though, I don't know if it's possible write because they both use the generator syntax to write. This might demonstrate the problem (contains a mix of yield-base and async-await syntax to demonstrate the difference between async calls and yields to the context manager). @contextmanager async

Context manager to validate data

China☆狼群 提交于 2019-12-29 08:22:29
问题 I'm trying to mull over a good solution to this and nothing is coming to mind. As an exercise, I'm trying to create a context manager that will handle data validation, something like: validation = lambda x: len(x) <= 10 with validator(validation): some_data = input("Please enter a name of 10 characters or less: ") print(some_data) # OUTPUT >> Please enter a name of 10 characters or less: FooBarSpamEggs >> Please enter a name of 10 characters of less: Adam Adam Originally I thought about doing

Context manager to validate data

我怕爱的太早我们不能终老 提交于 2019-12-29 08:22:20
问题 I'm trying to mull over a good solution to this and nothing is coming to mind. As an exercise, I'm trying to create a context manager that will handle data validation, something like: validation = lambda x: len(x) <= 10 with validator(validation): some_data = input("Please enter a name of 10 characters or less: ") print(some_data) # OUTPUT >> Please enter a name of 10 characters or less: FooBarSpamEggs >> Please enter a name of 10 characters of less: Adam Adam Originally I thought about doing

How can a Python context manager try to execute code?

こ雲淡風輕ζ 提交于 2019-12-24 17:09:13
问题 I'm trying to write a small context manager that'll try to execute some code repeatedly until the code works or until a specified number of tries has been made. I have attempted to write this but am encountering a difficulty with having the context manager handle problems when yielding: Exception RuntimeError: 'generator ignored GeneratorExit' How should I code this? import contextlib import random def main(): with nolube(): print(1 / random.randint(0, 1)) @contextlib.contextmanager def

python asynchronous context manager

隐身守侯 提交于 2019-12-24 00:59:28
问题 In Python Lan Ref. 3.4.4, it is said that __aenter__() and __aexit__() must return awaitables. However, in the example async context manager, these two methods return None: class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context') Is this code correct? 回答1: Your __aenter__ method must return a context. class MyAsyncContextManager: async def __aenter__(self): await log('entering context') #

Context Managers in Matlab: Invoking __enter__ in Matlab

允我心安 提交于 2019-12-22 17:54:02
问题 I have a python package and I would like to use its classes and methods in Matlab. I know that this can be done directly since Matlab 2014b. I mean all you have to do is add py. in the beginning of your statements. So far so good, however, I couldn't figure out how to deal with context managers through MATLAB, which are invoked using the with statement. For instance, assume that we have the following class in a module called app.py, class App(object): def __init__(self, input): self._input =

Using threading.Lock as context manager

不想你离开。 提交于 2019-12-22 03:43:24
问题 In the documentation of the threading module it says: All of the objects provided by this module that have acquire() and release() methods can be used as context managers for a with statement. The acquire() method will be called when the block is entered, and release() will be called when the block is exited. I was wondering if it is called in blocking or non-blocking mode? 回答1: From looking at the CPython source, it appears that it's called with default arguments, which means in blocking

python's `with` statement target is unexpectedly None

被刻印的时光 ゝ 提交于 2019-12-18 19:05:47
问题 seems like I do not understand something with---the python with statement. Consider this class: class test(object): def __enter__(self): pass def __exit__(self, *ignored): pass now, when using it with with , like in with test() as michael: print repr(michael) I would expect some output like <test instance at memore blah> . But I get None . Something wrong here? Any suggestions would help. (I am using Python 2.6.6.) EDIT: Thanks to ephement for pointing me to the documentation. The __enter__

python contextmanager newline issue

烂漫一生 提交于 2019-12-18 08:49:23
问题 Using Python's contextmanager I want to generate a wrapper to display Linux-like progress of a certain block of code: Doing something... done. [42 ms] This is working - kind of: from contextlib import contextmanager import time @contextmanager def msg(m): print(m + "... ", end='') t_start = time.time() yield t_duration_ms = 1000 * (time.time() - t_start) print("done. [{:.0f} ms]".format(t_duration_ms)) This usage example should print "Doing something... " without a line break, wait for a

File open and close in python

放肆的年华 提交于 2019-12-18 04:08:15
问题 I have read that when file is opened using the below format with open(filename) as f: #My Code f.close() explicit closing of file is not required . Can someone explain why is it so ? Also if someone does explicitly close the file, will it have any undesirable effect ? 回答1: The mile-high overview is this: When you leave the nested block, Python automatically calls f.close() for you. It doesn't matter whether you leave by just falling off the bottom, or calling break / continue / return to jump