with-statement

What's the advantage of using 'with .. as' statement in Python?

好久不见. 提交于 2019-11-27 22:48:17
with open("hello.txt", "wb") as f: f.write("Hello Python!\n") seems to be the same as f = open("hello.txt", "wb") f.write("Hello Python!\n") f.close() What's the advantage of using open .. as instead of f = ? Is it just syntactic sugar? Just saving one line of code? mg. In order to be equivalent to the with statement version, the code you wrote should look instead like this: f = open("hello.txt", "wb") try: f.write("Hello Python!\n") finally: f.close() While this might seem like syntactic sugar, it ensures that you release resources. Generally the world is more complex than these contrived

Python Conditional “With” Lock Design

☆樱花仙子☆ 提交于 2019-11-27 17:25:54
问题 I am trying to do some shared locking using with statements def someMethod(self, hasLock = False): with self.my_lock: self.somethingElse(hasLock=True) def somethingElse(self, hasLock = False): #I want this to be conditional... with self.my_lock: print 'i hate hello worlds" That make sense? I basically only want to do the with if I don't already have the lock. On top of being able to accomplish this, is it a bad design? Should I just acquire/release myself? 回答1: Just use a threading.RLock

tempfile.TemporaryDirectory context manager in Python 2.7

你离开我真会死。 提交于 2019-11-27 17:05:44
问题 Is there a way to create a temporary directory in a context manager with Python 2.7? with tempfile.TemporaryDirectory() as temp_dir: # modify files in this dir # here the temporary diretory does not exist any more. 回答1: Another option is the "backports.tempfile" package on pypi: https://pypi.python.org/pypi/backports.tempfile Quoting the project's description: "This package provides backports of new features in Python’s tempfile module under the backports namespace." Install with: pip install

Reference object instance created using “with” in Delphi

心不动则不痛 提交于 2019-11-27 15:11:01
is there a way to reference an object instance that is created using the "with" statement? Example: with TAnObject.Create do begin DoSomething(instance); end; Where DoSomething would use the instance reference as if you were passing an instance from a variable declared reference to the object created. Example: AnObject := TAnObject.Create; Thanks. Well, you can use such approach: // implement: type TSimpleMethod = procedure of object; function GetThis(const pr: TSimpleMethod): TObject; begin Result := TMethod(pr).Data; end; // usage: with TStringList.Create do try CommaText := '1,2,3,4,5,6,7,8

How to access the object itself in With … End With

北城余情 提交于 2019-11-27 15:03:34
Some code to illustrate my question: With Test.AnObject .Something = 1337 .AnotherThing = "Hello" ''// why can't I do this to pass the object itself: Test2.Subroutine(.) ''// ... and is there an equivalent, other than repeating the object in With? End With There is no way to refer to the object referenced in the With statement, other than repeating the name of the object itself. EDIT If you really want to, you could modify your AnObject to return a reference to itself Public Function Self() as TypeOfAnObject Return Me End Get Then you could use the following code With Test.AnObject Test2

How to avoid accidentally implicitly referring to properties on the global object?

眉间皱痕 提交于 2019-11-27 14:27:31
Is it possible to execute a block of code without the implicit with(global) context that all scripts seem to have by default? For example, in a browser, would there be any way to set up a script so that a line such as const foo = location; throws Uncaught ReferenceError: location is not defined instead of accessing window.location , when location has not been declared first? Lacking that, is there a way that such an implicit reference could result in a warning of some sort? It can be a source of bugs when writing code (see below), so having a way to guard against it could be useful. (Of course

Alternative to contextlib.nested with variable number of context managers

我怕爱的太早我们不能终老 提交于 2019-11-27 14:18:26
We have code that invokes a variable number of context managers depending on runtime parameters: from contextlib import nested, contextmanager @contextmanager def my_context(arg): print("entering", arg) try: yield arg finally: print("exiting", arg) def my_fn(items): with nested(*(my_context(arg) for arg in items)) as managers: print("processing under", managers) my_fn(range(3)) However, contextlib.nested is deprecated since Python 2.7 : DeprecationWarning: With-statements now directly support multiple context managers The answers to Multiple variables in Python 'with' statement indicate that

Implementing use of 'with object() as f' in custom class in python

孤街醉人 提交于 2019-11-27 13:36:58
问题 I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do with the garbage collector and such, I'm still not used to not knowing exactly when my objects are being deleted =\ The reason I was doing this is because I have to use tcsetattr

Skipping execution of -with- block

大憨熊 提交于 2019-11-27 10:55:26
问题 I am defining a context manager class and I would like to be able to skip the block of code without raising an exception if certain conditions are met during instantiation. For example, class My_Context(object): def __init__(self,mode=0): """ if mode = 0, proceed as normal if mode = 1, do not execute block """ self.mode=mode def __enter__(self): if self.mode==1: print 'Exiting...' CODE TO EXIT PREMATURELY def __exit__(self, type, value, traceback): print 'Exiting...' with My_Context(mode=1):

Using python “with” statement with try-except block

和自甴很熟 提交于 2019-11-27 10:46:28
Is this the right way to use the python "with" statement in combination with a try-except block?: try: with open("file", "r") as f: line = f.readline() except IOError: <whatever> If it is, then considering the old way of doing things: try: f = open("file", "r") line = f.readline() except IOError: <whatever> finally: f.close() Is the primary benefit of the "with" statement here that we can get rid of three lines of code? It doesn't seem that compelling to me for this use case (though I understand that the "with" statement has other uses). EDIT: Is the functionality of the above two blocks of