with-statement

python 'with' statement, should I use contextlib.closing?

喜欢而已 提交于 2019-12-03 05:14:57
from contextlib import closing def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) db.commit() This is from flask tutorial Step 3( http://flask.pocoo.org/docs/tutorial/dbinit/#tutorial-dbinit ). And I'm little curious about the line 4 of that. Must I import and use that 'contextlib.closing()' method? When I've learned about with statement, many articles said that it closes file automatically after process like below.(same as Finally: thing.close()) with open('filename','w') as f: f.write(someString); Even though I don

Oracle SQL insert into with With clause

匆匆过客 提交于 2019-12-03 04:38:37
I'm new to sql, so maybe it is a dumb question, but is there any possibility to use With clause with Insert Into? Or are there any common workarounds? I mean something like this: With helper_table As ( Select * From dummy2 ) Insert Into dummy1 Values (Select t.a From helper_table t Where t.a = 'X' ); Thx! My example is too dummy, so I add some extended code (thx for the answers so far). INSERT INTO dummy values (a,b) //more values WITH helper_table AS ( SELECT * FROM dummy2 ) WITH helper_table2 AS //from more tables ( SELECT * FROM dummy3 ) SELECT t.value as a, t2.value as b FROM helper_table

Finding Functions Defined in a with: Block

假如想象 提交于 2019-12-02 18:30:32
Here's some code from Richard Jones' Blog : with gui.vertical: text = gui.label('hello!') items = gui.selection(['one', 'two', 'three']) with gui.button('click me!'): def on_click(): text.value = items.value text.foreground = red My question is: how the heck did he do this? How can the context manager access the scope inside the with block? Here's a basic template for trying to figure this out: from __future__ import with_statement class button(object): def __enter__(self): #do some setup pass def __exit__(self, exc_type, exc_value, traceback): #XXX: how can we find the testing() function?

StringIO and compatibility with 'with' statement (context manager)

醉酒当歌 提交于 2019-12-02 17:00:07
I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below. What I want to do is not have to write to disk with some content that I generate in order to use this legacy function, so I though I could use StringIO to create an object in place of the physical filename. However, this does not work, as you can see below. I thought StringIO was the way to go with this. Can anyone tell me if there is a way to use this legacy function and pass it something in the argument that isn't a file on disk but

With statement in python is returning None object even though __init__ method works

巧了我就是萌 提交于 2019-12-02 00:09:12
问题 For a DB class with the following init method: class DB: def __init__(self, dbprops): self.dbprops = dbprops self.conn = self.get_connection(self.dbprops) debug("self.conn is %s" %self.conn) def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if not self.conn is None: self.close() And for a client method invoking it as follows: with DB(self.dbprops) as db: if not db: raise Exception("Db is None inside with") return db.get_cmdline_sql() The output shows the debug message -

Chain dynamic iterable of context managers to a single with statement

馋奶兔 提交于 2019-12-01 22:18:01
I have a bunch of context managers that I want to chain. On the first glance, contextlib.nested looked like a fitting solution. However, this method is flagged as deprecated in the documentation which also states that the latest with statement allows this directly: Deprecated since version 2.7: The with-statement now supports this functionality directly (without the confusing error prone quirks). However I could not get Python 3.4.3 to use a dynamic iterable of context managers: class Foo(): def __enter__(self): print('entering:', self.name) return self def __exit__(self, *_): pass def __init_

With statement in python is returning None object even though __init__ method works

浪子不回头ぞ 提交于 2019-12-01 21:16:24
For a DB class with the following init method: class DB: def __init__(self, dbprops): self.dbprops = dbprops self.conn = self.get_connection(self.dbprops) debug("self.conn is %s" %self.conn) def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if not self.conn is None: self.close() And for a client method invoking it as follows: with DB(self.dbprops) as db: if not db: raise Exception("Db is None inside with") return db.get_cmdline_sql() The output shows the debug message - thus the init method was successfully called: File "./classifier_wf.py", line 28, in get_cmdline_mysql

Is it wise to use with with statements in generators?

a 夏天 提交于 2019-12-01 19:01:05
Consider the following Python code: def values(): with somecontext(): yield 1 yield 2 for v in values(): print(v) break In this case, does Python guarantee that the generator is properly closed and, thus, that the context is exited? I realize that it, in practice, is going to be the case in CPython due to reference counting and eager destruction of the generator, but does Python guarantee this behavior? I do notice that it does indeed not work in Jython, so should that be considered a bug or allowable behavior? Yes, you can use a with statement in a generator without issue. Python will handle

with statement work on class

假装没事ソ 提交于 2019-12-01 05:52:10
问题 {class foo(object): def __enter__ (self): print("Enter") def __exit__(self,type,value,traceback): print("Exit") def method(self): print("Method") with foo() as instant: instant.method()} Execute this py file and console shows these message: Enter Exit instant.method() AttributeError: 'NoneType' object has no attribute 'method' unable to find methods? 回答1: __enter__ should return self : class foo(object): def __enter__ (self): print("Enter") return self def __exit__(self,type,value,traceback):

Python 2.5.2- what was instead of 'with' statement

天大地大妈咪最大 提交于 2019-12-01 04:52:32
I wrote my code for python 2.7 but the server has 2.5. How do i rewrite the next code so it will run in python 2.5.2: gzipHandler = gzip.open(gzipFile) try: with open(txtFile, 'w') as out: for line in gzipHandler: out.write(line) except: pass Right now, when i try to run my script I get this error: Warning: 'with' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "Main.py", line 7, in from Extractor import Extractor File "/data/client/scripts/Extractor.py", line 29 with open(self._logFile, 'w') as out: ^ SyntaxError: invalid syntax Thanks, Ron. In Python 2.5,