with-statement

Catching exception in context manager __enter__()

烂漫一生 提交于 2019-11-27 00:29:49
问题 Is it possible to ensure the __exit__() method is called even if there is an exception in __enter__() ? >>> class TstContx(object): ... def __enter__(self): ... raise Exception('Oops in __enter__') ... ... def __exit__(self, e_typ, e_val, trcbak): ... print "This isn't running" ... >>> with TstContx(): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in __enter__ Exception: Oops in __enter__ >>> Edit This is as close as I could get...

Break or exit out of “with” statement?

北战南征 提交于 2019-11-27 00:22:00
问题 I'd just like to exit out of a with statement under certain conditions: with open(path) as f: print 'before condition' if <condition>: break #syntax error! print 'after condition' Of course, the above doesn't work. Is there a way to do this? (I know that I can invert the condition: if not <condition>: print 'after condition' -- any way that is like above?) 回答1: The best way would be to encapsulate it in a function and use return : def do_it(): with open(path) as f: print 'before condition' if

In Python, if I return inside a “with” block, will the file still close?

走远了吗. 提交于 2019-11-26 23:58:53
问题 Consider the following: with open(path, mode) as f: return [line for line in f if condition] Will the file be closed properly, or does using return somehow bypass the context manager? 回答1: Yes, it acts like the finally block after a try block, i.e. it always executes (unless the python process terminates in an unusual way of course). It is also mentioned in one of the examples of PEP-343 which is the specification for the with statement: with locked(myLock): # Code here executes with myLock

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

元气小坏坏 提交于 2019-11-26 23:13:15
问题 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? 回答1: 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

UDF returns the same value everywhere

元气小坏坏 提交于 2019-11-26 21:58:22
问题 I am trying to code in moving average in vba but the following returns the same value everywhere. Function trial1(a As Integer) As Variant Application.Volatile Dim rng As Range Set rng = Range(Cells(ActiveCell.Row, 2), Cells(ActiveCell.Row - a + 1, 2)) trial1 = (Application.Sum(rng)) * (1 / a) End Function 回答1: The ActiveCell property does not belong in a UDF because it changes . Sometimes, it is not even on the same worksheet. If you need to refer to the cell in which the custom UDF function

Object becomes None when using a context manager

两盒软妹~` 提交于 2019-11-26 21:49:49
问题 Why doesn`t this work: class X: var1 = 1 def __enter__(self): pass def __exit__(self, type, value, traceback): pass with X() as z: print z.var1 I get: print z.var1 AttributeError: 'NoneType' object has no attribute 'var1' 回答1: Change the definition of X to class X(object): var1 = 1 def __enter__(self): return self def __exit__(self, type, value, traceback): pass with assigns the return value of the __enter__() method to the name after as . Your __enter__() returned None , which was assigned

Context manager for Python's MySQLdb

家住魔仙堡 提交于 2019-11-26 20:00:31
问题 I am used to (spoiled by?) python's SQLite interface to deal with SQL databases. One nice feature in python's SQLite's API the "context manager," i.e., python's with statement. I usually execute queries in the following way: import as sqlite with sqlite.connect(db_filename) as conn: query = "INSERT OR IGNORE INTO shapes VALUES (?,?);" results = conn.execute(query, ("ID1","triangle")) With the code above, if my query modifies the database and I forget to run conn.commit() ,the context manager

Equivalence of “With…End With” in C#? [duplicate]

故事扮演 提交于 2019-11-26 19:07:52
This question already has an answer here: With block equivalent in C#? 15 answers I know that C# has the using keyword, but using disposes of the object automatically. Is there the equivalence of With...End With in Visual Basic 6.0 ? C# doesn't have an equivalent language construct for that. It's not equivalent, but would this syntax work for you? Animal a = new Animal() { SpeciesName = "Lion", IsHairy = true, NumberOfLegs = 4 }; There is no equivalent, but I think discussing a syntax might be interesting! I quite like; NameSpace.MyObject. { active = true; bgcol = Color.Red; } Any other

Why should I not use “with” in Delphi?

試著忘記壹切 提交于 2019-11-26 17:57:30
I've heard many programmers, particularly Delphi programmers scorn the use of 'with'. I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting). Here's an example: procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32); begin with ARect do FillRectS(Left, Top, Right, Bottom, Value); end; I like using with . What's wrong with me? One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult. A bigger problem is that it

Multiple variables in a 'with' statement?

﹥>﹥吖頭↗ 提交于 2019-11-26 17:05:25
Is it possible to declare more than one variable using a with statement in Python? Something like: from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) ... or is cleaning up two resources at the same time the problem? Rafał Dowgird It is possible in Python 3 since v3.1 and Python 2.7 . The new with syntax supports multiple context managers: with A() as a, B() as b, C() as c: doSomething(a,b,c) Unlike the contextlib.nested , this guarantees that a and b will have their __exit__() 's called even if C() or