PyDev is reporting import errors which don't exist. The initial symptom was a fake "unresolved import" error, which was fixed by some combination of:
- Cleaning the Project
- Re-indexing the project (remove interpreter, add again)
- Restarting Eclipse
- Burning incense to the Python deities
Now the error is "unverified variable from import"--it can't seem to find pymssql.connect.
This IS NOT a PYHTONPATH problem. I can access the module just fine, the code in the file with the (alleged) error runs fine---it has unit tests and production code calling it.
The error is somewhere in PyDev: I added a new module to my PyDev project, and the error only occurs in the new module. I've tried all of the above.
So, I was planning on posting this code somewhere else to solicit some comments about the design, and I was asked in the comments to post code. (Inspired by: Database connection wrapper and Clint Miller's answer to this question: How do I correctly clean up a Python object?). The import error happens at line 69 (self.connection = pymssql.connect...). Not sure what good this does in answering the question, but...
import pymssql
from util.require_type import require_type
class Connections(object):
@require_type('host', str)
@require_type('user', str)
@require_type('password', str)
@require_type('database', str)
@require_type('as_dict', bool)
def __init__(self, host, user, password, database, as_dict=True):
self.host = host
self.user = user
self.password = password
self.db = database
self.as_dict = as_dict
@staticmethod
def server1(db):
return Connections('','','','')
@staticmethod
def server2(db):
pass
@staticmethod
def server3(db):
pass
class DBConnectionSource(object):
# Usage:
# with DBConnectionSource(ConnectionParameters.server1(db = 'MyDB)) as dbConn:
# results = dbConn.execute(sqlStatement)
@require_type('connection_parameters', Connections)
def __init__(self, connection_parameters=Connections.server1('MyDB')):
self.host = connection_parameters.host
self.user = connection_parameters.user
self.password = connection_parameters.password
self.db = connection_parameters.db
self.as_dict = connection_parameters.as_dict
self.connection = None
def __enter__(self):
parent = self
class DBConnection(object):
def connect(self):
self.connection = pymssql.connect(host=parent.host,
user=parent.user,
password=parent.password,
database=parent.db,
as_dict=parent.as_dict)
def execute(self, sqlString, arguments={}):
if self.connection is None:
raise Exception('DB Connection not defined')
crsr = self.connection.cursor()
crsr.execute(sqlString, arguments)
return list(crsr)
def cleanup(self):
if self.connection:
self.connection.close()
self.connection = DBConnection()
self.connection.connect()
return self.connection
def __exit__(self, typ, value, traceback):
self.connection.cleanup()