To answer the 2nd part of your question ...
You should invoke class Console
using the with
statement. This will automatically call __enter__
and __exit__
routines. For example:
class CM(object):
def __init__(self, arg):
print 'Initializing arg .. with', arg
def __enter__(self):
print 'Entering CM'
def __exit__(self, type, value, traceback):
print 'Exiting CM'
if type is IndexError:
print 'Oh! .. an Index Error! .. must handle this'
print 'Lets see what the exception args are ...', value.args
return True
Running it:
with CM(10) as x:
print 'Within CM'
Output:
Initializing arg .. with 10
Entering CM
Within CM
Exiting CM
The arguments to __exit__
are related to exceptions. If there are no exceptions when you exit the with statement then all arguments (exception_type, exception_instance, exception_traceback) will be None
. Here's an example showing how the exit arguments can be used ...
Example with an exception:
with CM(10) as x:
print 'Within CM'
raise IndexError(1, 2, 'dang!')
Output:
Initializing arg .. with 10
Entering CM
Within CM
Exiting CM
Oh! .. an Index Error! .. must handle this
Lets see what the exception args are ... (1, 2, 'dang!')
Check out "With-Statement" and "Context Managers" here ..
http://docs.python.org/2/reference/compound_stmts.html#with
http://docs.python.org/2/reference/datamodel.html#context-managers