contextmanager

Passing arguments to decontext decorator

£可爱£侵袭症+ 提交于 2019-12-11 09:54:38
问题 I have a helper class Decontext that I am using to turn a context manager into a decorator (pyton 2.6). class Decontext(object): """ makes a context manager also act as decorator """ def __init__(self, context_manager): self._cm = context_manager def __enter__(self): return self._cm.__enter__() def __exit__(self, *args, **kwds): return self._cm.__exit__(*args, **kwds) def __call__(self, func): def wrapper(*args, **kwds): with self: return func(*args, **kwds) return wrapper My contextmanager

With-Statement and Threading :Making function execute before run

浪尽此生 提交于 2019-12-11 05:38:37
问题 This question is a follow up from following question:With statement and python threading I have been experimenting with python threading api. I have this code which works for what I want to achieve :---->function execution before invoking run on python thread. However to do this, I invariably have to call time.sleep(1) in the run() method to make it proceed to execute().Otherwise the thread exits without function assignment and execution.Is there a better way to achieve this type of waiting?

Python ctypes from_buffer mapping with context manager into memory mapped file (mmap)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 04:37:35
问题 I'm using ctypes.from_buffer() to map a ctypes structure to a memory mapped file for some tasks. Typically, these files contain a concatenation of structured headers and binary data. The ctypes structure allows for a stable binary representation and easy pythonic access of the fields - a real winning team in this respect. These memory mapped files grow dynamically over time. Apart from the complication of accepting growth in mmap.PAGESIZE granularity only, the mmap responds with allergic

Does Context/Scoping of a SQLAlchemy Session Require Non-Automatic Object/Attribute Expiration?

ⅰ亾dé卋堺 提交于 2019-12-11 02:08:14
问题 The Situation: Simple Class with Basic Attributes In an application I'm working on, instances of particular class are persisted at the end of their lifecycle, and while they are not subsequently modified, their attributes may need to be read. For example, the end_time of the instance or its ordinal position relative to other instances of the same class (first instance initialized gets value 1, the next has value 2, etc.). class Foo(object): def __init__(self, position): self.start_time = time

Catching an exceptions in __enter__ in the calling code in Python

删除回忆录丶 提交于 2019-12-10 20:27:04
问题 Is there a way I can catch exceptions in the __enter__ method of a context manager without wrapping the whole with block inside a try ? class TstContx(object): def __enter__(self): raise Exception("I'd like to catch this exception") def __exit__(self, e_typ, e_val, trcbak): pass with TstContx(): raise Exception("I don't want to catch this exception") pass I know that I can catch the exception within __enter__() itself, but can I access that error from the function that contains the with

attempting to replace open() with a pandas subset, but I am given an __exit__ error?

独自空忆成欢 提交于 2019-12-10 18:27:37
问题 I am trying to work with pylabels to create nametags for an upcoming event. In one section of the code, there is this tid-bit: with open(os.path.join(base_path, "names.txt")) as names: sheet.add_labels(name.strip() for name in names) where sheet = labels.Sheet(specs, write_name, border=True) . So essentially, this will load each line of "names.txt" and call the function 'write_name', using specifications in 'specs', and add each name to unique labels. I'm attempting to change this code to the

How to use a context manager inside a decorator and how to pass an object created in decorator to decorated function

陌路散爱 提交于 2019-12-10 18:12:14
问题 I have a test class which requires to do some cleanup at the end. To make sure that the user won't forget to do this, I want to add a context manager to the class. I also have a decorator, inside which I want to use this context manager to create an object of test class and pass it to the decorated function. Is it even possible? This is what I am looking to do: class test: def __init__(self, name): self._name = name print "my name is {0}".format(name) def exit(): print "exiting"

Nest an iterator of Python context managers in “with”

馋奶兔 提交于 2019-12-10 16:19:04
问题 I have an iterator that returns context managers. I want a pythonic with statement, that emulates the behaviour of several nested with statements, one for each context manager returned by the iterator. One could say, I want a generalisation of the (deprecated) contextlib.nested function. 回答1: From the docs: Developers that need to support nesting of a variable number of context managers can either use the warnings module to suppress the DeprecationWarning raised by [ contextlib.nested ] or

Temporarily changing a variable's value in Python

前提是你 提交于 2019-12-10 13:06:46
问题 Python 3.4 provides this neat tool to temporarily redirect stdout: # From https://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout with redirect_stdout(sys.stderr): help(pow) The code is not super-complicated, but I wouldn't want to write it over and over again, especially since some thought has gone into it to make it re-entrant: class redirect_stdout: def __init__(self, new_target): self._new_target = new_target # We use a list of old targets to make this CM re-entrant

Writing a Python class that can only be used as a context manager [duplicate]

余生颓废 提交于 2019-12-10 04:15:13
问题 This question already has answers here : How to check if an object is created with `with` statement? (5 answers) Closed 4 years ago . Is there a way in Python to write a class that will error unless it's used with a with statement? # Okay: with Foo() as f1: f1.func1() f1.func2() # Not okay: f2 = Foo() f2.func1() I can do it manually: have __enter__ set a flag and have every other method check for that flag. But is there a nicer way to do it? Here's code for the not-so-since way: class Foo