Some background: I work in a large bank and I'm trying to re-use some Python modules, which I cannot change, only import. I also don't have the option of installing any new utilities/functions etc (running Python 2.6 on Linux).
I've got this at present:
In my module:
from common.databaseHelper import BacktestingDatabaseHelper
class mfReportProcess(testingResource):
def __init__(self):
self.db = BacktestingDatabaseHelper.fromConfig('db_name')
One of the methods called within the 'testingResource' class has this:
with self.db as handler:
which falls over with this:
with self.db as handler:
AttributeError: 'BacktestingDatabaseHelper' object has no attribute '__exit__'
and, indeed, there is no __exit__
method in the 'BacktestingDatabaseHelper' class, a class which I cannot change.
However, this code I'm trying to re-use works perfectly well for other apps - does anyone know why I get this error and no-one else?
Is there some way of defining __exit__
locally?
Many thanks in advance.
EDITED to add:
I've tried to add my own class to setup DB access but can't get it to work - added this to my module:
class myDB(BacktestingDatabaseHelper):
def __enter__(self):
self.db = fromConfig('db_name')
def __exit__(self):
self.db.close()
and added:
self.db = myDB
into my init attribute for my main class but I get this error:
with self.db as handler:
TypeError: unbound method __enter__() must be called with myDB instance as first argument (got nothing instead)
Any suggestions as to how to do this properly?
__exit__ in Python Context manager is used for managing resources used by the program. After completion of usage, we have to release memory and terminate connections between files.
Once the code block is entered, __exit__ is always called, even if an exception is raised in the code block. If __exit__ returns True , the exception is suppressed.
__exit__() is an abstract method which by default returns None . See also the definition of Context Manager Types. New in version 3.6. An abstract base class for classes that implement object.
exc_type. Python defines a TracebackException class that accepts an exc_type argument which is used contextually in the constructor within issubclass with SyntaxError , which infers that exc_type is indeed some sort of Exception , which SyntaxError inherits from.
Using the with
protocol assumes that the object used in with
implements the context manager protocol.
Basically this means that the class definition should have __enter__()
and __exit__()
methods defined. If you use an object without these, python will throw an AttributeError
complaining about the missing __exit__
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With