Feature request: "with" support for connection and cursor
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
MySQL Connector/Python |
Triaged
|
Wishlist
|
Geert JM Vanderkelen |
Bug Description
I like this very much because it shortens the code:
////// ON THE CONNECTION ////////////////
with mysq.connector.
c.execute(
row = c.fetchone()
...
def __enter__(self):
""" For the /with/ statement:
Enter the runtime context related to this object.
The with statement will bind this method's return value to the target(s) specified in the as clause of the statement, if any.
"""
return self.cursor()
def __exit__(self, exc_type, exc_value, traceback):
""" For the /with/ statement:
Exit the runtime context related to this object.
The parameters describe the exception that caused the context to be exited.
If the context was exited without an exception, all three arguments will be None.
If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated),
it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.
Note that __exit__() methods should not reraise the passed-in exception; this is the caller's responsibility.
"""
for c in self.cursors: c.close() # don't know if this is really necessary if we close the connection in the next line (?!)
del self # to be nice on the garbage collector (?!)
////// ON THE CURSOR ////////////////
conn = mysq.connector.
with conn.cursor() as c:
c.execute(
row = c.fetchone()
...
<<< this is less interesting because it saves only the close() .... (so: like for opening files in the with statement :)
... but still one line less :)
... and to be consistent
def __enter__(self):
""" For the /with/ statement:
Enter the runtime context related to this object.
The with statement will bind this method's return value to the target(s) specified in the as clause of the statement, if any.
"""
pass
def __exit__(self, exc_type, exc_value, traceback):
""" For the /with/ statement:
Exit the runtime context related to this object.
The parameters describe the exception that caused the context to be exited.
If the context was exited without an exception, all three arguments will be None.
If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated),
it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.
Note that __exit__() methods should not reraise the passed-in exception; this is the caller's responsibility.
"""
#del self # this should be unnecessary because its done by close(), right ?!
Changed in myconnpy: | |
importance: | Undecided → Wishlist |
status: | New → Triaged |
assignee: | nobody → Geert JM Vanderkelen (geertjmvdk) |