Reputation: 3011
I am working on a simple convenience class to use with the with
operator so that I can establish exclusive access to a sqlite3 database for a extended writing session in a concurrent system.
Here is the class:
import sqlite3 as sql
class ExclusiveSqlConnection(object):
"""meant to be used with a with statement to ensure proper closure"""
def __enter__(self, path):
self.con = sql.connect(path, isolation_level = "EXCLUSIVE")
self.con.execute("BEGIN EXCLUSIVE")
self.cur = self.con.cursor()
return self
def __exit__(self):
self.con.commit()
self.con.close()
However, when I run this I get the error:
with sql_lib.ExclusiveSqlConnection(self.output) as c:
TypeError: object.__new__() takes no parameters
Upvotes: 1
Views: 47
Reputation: 7591
The constructor (__init__
method) for your ExclusiveSqlConnection
needs to take a path
parameter.
On the other hand, __enter__
takes no parameter other than self
.
import sqlite3 as sql
class ExclusiveSqlConnection(object):
"""meant to be used with a with statement to ensure proper closure"""
def __init__(self, path):
self.path = path
def __enter__(self):
self.con = sql.connect(self.path, isolation_level = "EXCLUSIVE")
self.con.execute("BEGIN EXCLUSIVE")
self.cur = self.con.cursor()
return self
def __exit__(self, exception_type, exception_val, trace):
self.con.commit()
self.con.close()
Upvotes: 2