desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns a copy of this object.'
def copy(self):
return self.__deepcopy__()
'update() extends rather than replaces existing key lists. Also accepts keyword args.'
def update(self, *args, **kwargs):
if (len(args) > 1): raise TypeError(('update expected at most 1 arguments, got %d' % len(args))) if args: other_dict = args[0] if isinstance(other_dict, MultiValueDict): for (key, value_list) in other_dict.lists(): self.setlistdefault(key,...
'Retrieves the real value after stripping the prefix string (if present). If the prefix is present, pass the value through self.func before returning, otherwise return the raw value.'
def __getitem__(self, key):
if key.startswith(self.prefix): use_func = True key = key[len(self.prefix):] else: use_func = False value = super(DictWrapper, self).__getitem__(key) if use_func: return self.func(value) return value
'Convenience method for adding an element with no children'
def addQuickElement(self, name, contents=None, attrs=None):
if (attrs is None): attrs = {} self.startElement(name, attrs) if (contents is not None): self.characters(contents) self.endElement(name)
'Constructs a new Node. If no connector is given, the default will be used. Warning: You probably don\'t want to pass in the \'negated\' parameter. It is NOT the same as constructing a node and calling negate() on the result.'
def __init__(self, children=None, connector=None, negated=False):
self.children = ((children and children[:]) or []) self.connector = (connector or self.default) self.subtree_parents = [] self.negated = negated
'This is called to create a new instance of this class when we need new Nodes (or subclasses) in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature that is not an extension of Node.__init__ might need to implement this method to allow a Node to create a...
def _new_instance(cls, children=None, connector=None, negated=False):
obj = Node(children, connector, negated) obj.__class__ = cls return obj
'Utility method used by copy.deepcopy().'
def __deepcopy__(self, memodict):
obj = Node(connector=self.connector, negated=self.negated) obj.__class__ = self.__class__ obj.children = deepcopy(self.children, memodict) obj.subtree_parents = deepcopy(self.subtree_parents, memodict) return obj
'The size of a node if the number of children it has.'
def __len__(self):
return len(self.children)
'For truth value testing.'
def __nonzero__(self):
return bool(self.children)
'Returns True is \'other\' is a direct child of this instance.'
def __contains__(self, other):
return (other in self.children)
'Adds a new node to the tree. If the conn_type is the same as the root\'s current connector type, the node is added to the first level. Otherwise, the whole tree is pushed down one level and a new root connector is created, connecting the existing tree and the new node.'
def add(self, node, conn_type):
if ((node in self.children) and (conn_type == self.connector)): return if (len(self.children) < 2): self.connector = conn_type if (self.connector == conn_type): if (isinstance(node, Node) and ((node.connector == conn_type) or (len(node) == 1))): self.children.extend(node....
'Negate the sense of the root connector. This reorganises the children so that the current node has a single child: a negated node containing all the previous children. This slightly odd construction makes adding new children behave more intuitively. Interpreting the meaning of this negate is up to client code. This me...
def negate(self):
self.children = [self._new_instance(self.children, self.connector, (not self.negated))] self.connector = self.default
'Sets up internal state so that new nodes are added to a subtree of the current node. The conn_type specifies how the sub-tree is joined to the existing children.'
def start_subtree(self, conn_type):
if (len(self.children) == 1): self.connector = conn_type elif (self.connector != conn_type): self.children = [self._new_instance(self.children, self.connector, self.negated)] self.connector = conn_type self.negated = False self.subtree_parents.append(self.__class__(self.child...
'Closes off the most recently unmatched start_subtree() call. This puts the current state into a node of the parent tree and returns the current instances state to be the parent.'
def end_subtree(self):
obj = self.subtree_parents.pop() node = self.__class__(self.children, self.connector) self.connector = obj.connector self.negated = obj.negated self.children = obj.children self.children.append(node)
'Must be implemented by subclasses to initialise the wrapped object.'
def _setup(self):
raise NotImplementedError
'Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value.'
def __init__(self, func):
self.__dict__['_setupfunc'] = func self._wrapped = None
'Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode ch...
def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None):
self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if (separators is not None): (self.item_separator, self.key_separator) = separators if (default is not None): ...
'Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return l...
def default(self, o):
raise TypeError(('%r is not JSON serializable' % (o,)))
'Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) \'{"foo": ["bar", "baz"]}\''
def encode(self, o):
if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if ((_encoding is not None) and (not (_encoding == 'utf-8'))): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: ...
'Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk)'
def iterencode(self, o, _one_shot=False):
if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if (self.encoding != 'utf-8'): def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): i...
'``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook...
def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True):
self.encoding = encoding self.object_hook = object_hook self.parse_float = (parse_float or float) self.parse_int = (parse_int or int) self.parse_constant = (parse_constant or _CONSTANTS.__getitem__) self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self...
'Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document)'
def decode(self, s, _w=WHITESPACE.match):
(obj, end) = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if (end != len(s)): raise ValueError(errmsg('Extra data', s, end, len(s))) return obj
'Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.'
def raw_decode(self, s, idx=0):
try: (obj, end) = self.scan_once(s, idx) except StopIteration: raise ValueError('No JSON object could be decoded') return (obj, end)
'\'a.m.\' or \'p.m.\''
def a(self):
if (self.data.hour > 11): return _('p.m.') return _('a.m.')
'\'AM\' or \'PM\''
def A(self):
if (self.data.hour > 11): return _('PM') return _('AM')
'Swatch Internet time'
def B(self):
raise NotImplementedError
'Time, in 12-hour hours and minutes, with minutes left off if they\'re zero. Examples: \'1\', \'1:30\', \'2:05\', \'2\' Proprietary extension.'
def f(self):
if (self.data.minute == 0): return self.g() return (u'%s:%s' % (self.g(), self.i()))
'Hour, 12-hour format without leading zeros; i.e. \'1\' to \'12\''
def g(self):
if (self.data.hour == 0): return 12 if (self.data.hour > 12): return (self.data.hour - 12) return self.data.hour
'Hour, 24-hour format without leading zeros; i.e. \'0\' to \'23\''
def G(self):
return self.data.hour
'Hour, 12-hour format; i.e. \'01\' to \'12\''
def h(self):
return (u'%02d' % self.g())
'Hour, 24-hour format; i.e. \'00\' to \'23\''
def H(self):
return (u'%02d' % self.G())
'Minutes; i.e. \'00\' to \'59\''
def i(self):
return (u'%02d' % self.data.minute)
'Time, in 12-hour hours, minutes and \'a.m.\'/\'p.m.\', with minutes left off if they\'re zero and the strings \'midnight\' and \'noon\' if appropriate. Examples: \'1 a.m.\', \'1:30 p.m.\', \'midnight\', \'noon\', \'12:30 p.m.\' Proprietary extension.'
def P(self):
if ((self.data.minute == 0) and (self.data.hour == 0)): return _('midnight') if ((self.data.minute == 0) and (self.data.hour == 12)): return _('noon') return (u'%s %s' % (self.f(), self.a()))
'Seconds; i.e. \'00\' to \'59\''
def s(self):
return (u'%02d' % self.data.second)
'Microseconds'
def u(self):
return self.data.microsecond
'Month, textual, 3 letters, lowercase; e.g. \'jan\''
def b(self):
return MONTHS_3[self.data.month]
'ISO 8601 Format Example : \'2008-01-02T10:30:00.000123\''
def c(self):
return self.data.isoformat()
'Day of the month, 2 digits with leading zeros; i.e. \'01\' to \'31\''
def d(self):
return (u'%02d' % self.data.day)
'Day of the week, textual, 3 letters; e.g. \'Fri\''
def D(self):
return WEEKDAYS_ABBR[self.data.weekday()]
'Month, textual, long; e.g. \'January\''
def F(self):
return MONTHS[self.data.month]
'\'1\' if Daylight Savings Time, \'0\' otherwise.'
def I(self):
if (self.timezone and self.timezone.dst(self.data)): return u'1' else: return u'0'
'Day of the month without leading zeros; i.e. \'1\' to \'31\''
def j(self):
return self.data.day
'Day of the week, textual, long; e.g. \'Friday\''
def l(self):
return WEEKDAYS[self.data.weekday()]
'Boolean for whether it is a leap year; i.e. True or False'
def L(self):
return calendar.isleap(self.data.year)
'Month; i.e. \'01\' to \'12\''
def m(self):
return (u'%02d' % self.data.month)
'Month, textual, 3 letters; e.g. \'Jan\''
def M(self):
return MONTHS_3[self.data.month].title()
'Month without leading zeros; i.e. \'1\' to \'12\''
def n(self):
return self.data.month
'Month abbreviation in Associated Press style. Proprietary extension.'
def N(self):
return MONTHS_AP[self.data.month]
'Difference to Greenwich time in hours; e.g. \'+0200\''
def O(self):
seconds = self.Z() return (u'%+03d%02d' % ((seconds // 3600), ((seconds // 60) % 60)))
'RFC 2822 formatted date; e.g. \'Thu, 21 Dec 2000 16:01:07 +0200\''
def r(self):
return self.format('D, j M Y H:i:s O')
'English ordinal suffix for the day of the month, 2 characters; i.e. \'st\', \'nd\', \'rd\' or \'th\''
def S(self):
if (self.data.day in (11, 12, 13)): return u'th' last = (self.data.day % 10) if (last == 1): return u'st' if (last == 2): return u'nd' if (last == 3): return u'rd' return u'th'
'Number of days in the given month; i.e. \'28\' to \'31\''
def t(self):
return (u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1])
'Time zone of this machine; e.g. \'EST\' or \'MDT\''
def T(self):
name = ((self.timezone and self.timezone.tzname(self.data)) or None) if (name is None): name = self.format('O') return unicode(name)
'Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)'
def U(self):
if getattr(self.data, 'tzinfo', None): return int(calendar.timegm(self.data.utctimetuple())) else: return int(time.mktime(self.data.timetuple()))
'Day of the week, numeric, i.e. \'0\' (Sunday) to \'6\' (Saturday)'
def w(self):
return ((self.data.weekday() + 1) % 7)
'ISO-8601 week number of year, weeks starting on Monday'
def W(self):
week_number = None jan1_weekday = (self.data.replace(month=1, day=1).weekday() + 1) weekday = (self.data.weekday() + 1) day_of_year = self.z() if ((day_of_year <= (8 - jan1_weekday)) and (jan1_weekday > 4)): if ((jan1_weekday == 5) or ((jan1_weekday == 6) and calendar.isleap((self.data.year ...
'Year, 2 digits; e.g. \'99\''
def y(self):
return unicode(self.data.year)[2:]
'Year, 4 digits; e.g. \'1999\''
def Y(self):
return self.data.year
'Day of the year; i.e. \'0\' to \'365\''
def z(self):
doy = (self.year_days[self.data.month] + self.data.day) if (self.L() and (self.data.month > 2)): doy += 1 return doy
'Time zone offset in seconds (i.e. \'-43200\' to \'43200\'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'
def Z(self):
if (not self.timezone): return 0 offset = self.timezone.utcoffset(self.data) return ((offset.days * 86400) + offset.seconds)
'Get information about any POST forms in the template. Returns [(linenumber, csrf_token added)]'
def post_form_info(self):
matches = [] for (ln, line) in enumerate(self.content.split('\n')): m = _POST_FORM_RE.search(line) if (m is not None): matches.append(((ln + 1), (_TOKEN_RE.search(line) is not None))) return matches
'Returns true if this template includes template \'t\' (via {% include %})'
def includes_template(self, t):
for r in t.relative_filenames: if re.search((('\\{%\\s*include\\s+(\\\'|")' + re.escape(r)) + '(\\1)\\s*%\\}'), self.content): return True return False
'Returns all templates that include this one, recursively. (starting with this one)'
def related_templates(self):
try: return self._related_templates except AttributeError: pass retval = set([self]) for t in self.all_templates: if t.includes_template(self): retval = retval.union(t.related_templates()) self._related_templates = retval return retval
'Convert a representation node to a Python object.'
def from_yaml(cls, loader, node):
return loader.construct_yaml_object(node, cls)
'Convert a Python object to a representation node.'
def to_yaml(cls, dumper, data):
return dumper.represent_yaml_object(cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style)
'Initialize the scanner.'
def __init__(self):
self.done = False self.flow_level = 0 self.tokens = [] self.fetch_stream_start() self.tokens_taken = 0 self.indent = (-1) self.indents = [] self.allow_simple_key = True self.possible_simple_keys = {}
'Instantiate a line-oriented interpreter framework. The optional argument \'completekey\' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alter...
def __init__(self, completekey='tab', stdin=None, stdout=None):
Cmd.__init__(self, completekey, stdin, stdout)
'Called by ``cmdloop`` on interrupt.'
def interrupted(self):
pass
'Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. This version is a direct rip-off of the parent class\'s ``cmdloop()`` method, with some changes to support SIGINT properly.'
def cmdloop(self, intro=None):
self.preloop() if (self.use_rawinput and self.completekey): try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind((self.completekey + ': complete')) except ImportError: ...
'Get list of commands, for completion. This version just edits the base class\'s results.'
def completenames(self, text, *ignored):
if text.startswith('.'): text = ('dot_' + text[1:]) commands = Cmd.completenames(self, text, ignored) result = [] for command in commands: if command.startswith('dot_'): result.append(('.' + command[4:])) else: result.append(command) return result
'Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). \'command\' and \'args\' may be None if the line couldn\'t be parsed. Overrides the parent class\'s version of this method, to handle dot commands.'
def parseline(self, line):
(cmd, arg, line) = Cmd.parseline(self, line) if (cmd and cmd.startswith('.')): s = 'dot' if (len(cmd) > 1): s += ('_%s' % cmd[1:]) cmd = s return (cmd, arg, line)
'Swiped from the base class\'s do_help() method and modified to handle dot commands better.'
def __do_help(self, arg):
if arg: if arg.startswith('.'): arg = ('dot_' + arg[1:]) try: func = getattr(self, ('help_' + arg)) func() except AttributeError: try: doc = getattr(self, ('do_' + arg)).__doc__ if doc: self.s...
'Re-run a command. Usage: r [num|string] redo [num|string] where \'num\' is the number of the command to re-run, as shown in the \'history\' display. \'string\' is a substring to match against the command history; for instance, \'r select\' attempts to run the last command starting with \'select\'. If called with no ar...
def do_redo(self, args):
do_r(args)
'Re-run a command. Usage: r [num|string] redo [num|string] where \'num\' is the number of the command to re-run, as shown in the \'history\' display. \'string\' is a substring to match against the command history; for instance, \'r select\' attempts to run the last command starting with \'select\'. If called with no ar...
def do_r(self, args):
a = args.split() if (len(a) > 1): raise BadCommandError, 'Too many parameters' if (len(a) == 0): line = self.__history.get_last_item() else: try: line = self.__history.get_item(int(a[0])) except ValueError: line = self.__history.get_last_matc...
'Run a SQL \'SELECT\' statement.'
def do_select(self, args):
self.__ensure_connected() cursor = self.__db.cursor() try: self.__handle_select(args, cursor) finally: cursor.close() if self.__flag_is_set('autocommit'): self.__db.commit()
'Run a SQL \'INSERT\' statement.'
def do_insert(self, args):
self.__handle_update('insert', args)
'Run a SQL \'UPDATE\' statement.'
def do_update(self, args):
self.__handle_update('update', args)
'Run a SQL \'DELETE\' statement.'
def do_delete(self, args):
self.__handle_update('delete', args)
'Run a SQL \'CREATE\' statement (e.g., \'CREATE TABLE\', \'CREATE INDEX\')'
def do_create(self, args):
self.__handle_update('create', args)
'Run a SQL \'ALTER\' statement (e.g., \'ALTER TABLE\', \'ALTER INDEX\')'
def do_alter(self, args):
self.__handle_update('alter', args)
'Run a SQL \'DROP\' statement (e.g., \'DROP TABLE\', \'DROP INDEX\')'
def do_drop(self, args):
self.__handle_update('drop', args)
'Begin a SQL transaction. This command is essentially a no-op: It\'s ignored in autocommit mode, and irrelevant when autocommit mode is off. It\'s there primarily for SQL scripts.'
def do_begin(self, args):
self.__ensure_connected() if self.__flag_is_set('autocommit'): log.warning('Autocommit is enabled. "begin" ignored')
'Commit the current transaction. Ignored if \'autocommit\' is enabled. (Autocommit is enabled by default.)'
def do_commit(self, args):
self.__ensure_connected() if self.__flag_is_set('autocommit'): log.warning('Autocommit is enabled. "commit" ignored') else: assert (self.__db != None) self.__db.commit()
'Roll the current transaction back. Ignored if \'autocommit\' is enabled. (Autocommit is enabled by default.)'
def do_rollback(self, args):
self.__ensure_connected() if self.__flag_is_set('autocommit'): log.warning('Autocommit is enabled. "rollback" ignored') else: assert (self.__db != None) self.__db.rollback()
'Handles an end-of-file on input.'
def do_EOF(self, args):
if self.__interactive: print '\nBye.' self.__save_history() if (self.__db != None): try: self.__db.close() except db.Warning as ex: log.warning(('%s' % str(ex))) except db.Error as ex: log.error(('%s' % str(ex))) return True
'Display information about sqlcmd. Takes no parameters.'
def do_dot_about(self, args):
import grizzled print VERSION_STAMP print ('(Using %s, version %s)' % (grizzled.title, grizzled.version))
'Exit sqlcmd. .exit is equivalent to typing the key sequence corresponding to an end-of-file condition (Ctrl-D on Unix systems, Ctrl-Z on Windows).'
def do_dot_exit(self, args):
self.cmdqueue += ['EOF']
'Handles a \'sset\' command, to set a sqlcmd variable. With no arguments, this command displays all sqlcmd settings and values. Usage: .set [setting value]'
def do_dot_set(self, args):
self.__echo('.set', args, add_semi=False) set_args = args.split() total_args = len(set_args) if (total_args == 0): self.__show_vars(self.__settings) return if (total_args != 2): raise BadCommandError, 'Incorrect number of arguments' self.__set_setting(set_args[0]...
'Show the current command history. Identical to the \'hist\' and \'history\' commands. Usage: .h'
def do_dot_h(self, args):
self.__show_history()
'Show the current command history. Identical to the \'h\' command and \'history\' commands. Usage: .hist'
def do_dot_hist(self, args):
self.__show_history()
'Show the current command history. Identical to the \'h\' command and \'hist\' commands. Usage: .history'
def do_dot_history(self, args):
self.__show_history()
'Run the ".show" command. There are several subcommands. .show database Show information about the connected database. .show tables [regexp] Show the names of all tables. If <regexp> is supplied, show only those tables whose names match the regular expression.'
def do_dot_show(self, args):
tokens = args.split(None) if (len(tokens) == 0): raise BadCommandError('Missing argument(s) to ".show".') cmd = tokens[0] if (cmd.lower() == 'tables'): if (len(tokens) > 2): raise BadCommandError('Usage: .show tables [regexp]') elif (len(tokens) == 1...
'Describe a table. Identical to the \'describe\' command. Usage: .desc tablename [full] If \'full\' is specified, then the tables indexes are displayed as well (assuming the underlying DB driver supports retrieving index metadata).'
def do_dot_desc(self, args):
self.do_dot_describe(args, cmd='.desc')
'Describe a table. Identical to the \'desc\' command. Usage: .describe tablename [full] If \'full\' is specified, then the tables indexes are displayed as well (assuming the underlying DB driver supports retrieving index metadata).'
def do_dot_describe(self, args, cmd='.describe'):
self.__ensure_connected() cursor = self.__db.cursor() try: self.__handle_describe(cmd, args, cursor) finally: cursor.close()
'Echo all remaining arguments to standard output. Useful for scripts. Usage: .echo [args]'
def do_dot_echo(self, args):
if args: args = args.strip() print args
'Load and run a file full of commands without exiting the command shell. Usage: .run file .load file'
def do_dot_load(self, args):
self.do_dot_run(args)
'Display the list of variables that can be substituted into other input lines. For example: ? table=mytable ? columns="color, size" ? .vars columns="color, size" table="mytable"'
def do_dot_vars(self, args):
if self.__variables: names = self.__variables.keys() names.sort() for name in names: print ('%s="%s"' % (name, self.__variables[name].replace('"', '\\"')))
'Set a variable that can be interpolated, shell style, within subsequent commands. For example: table=mytable select * from $mytable; Usage: .var name=value name=value'
def do_dot_var(self, args):
match = VARIABLE_ASSIGNMENT_RE.match(args) if (not match): raise BadCommandError('Illegal .var command.') variable = match.group(1) value = match.group(2) value = value.strip() if (value[0] in ('"', "'")): if (value[(-1)] != value[0]): log.error(('Missing end...
'Load and run a file full of sqlcmd commands without exiting the SQL command shell. After the contents of the file have been run through sqlcmd, you will be prompted again for interactive input (if sqlcmd is running interactively). Usage: .run file .load file'
def do_dot_run(self, args):
tokens = args.split(None, 1) if (len(tokens) > 1): raise BadCommandError, 'Too many arguments to ".load"' try: self.__run_file(os.path.expanduser(tokens[0])) except IOError as (ex, msg): log.error(('Unable to load file "%s": %s' % (tokens[0], msg)))
'Close the current database connection, and connect to another database. Usage: .connect database_alias where \'database_alias\' is a valid database alias from the .sqlcmd startup file.'
def do_dot_connect(self, args):
tokens = args.split(None, 1) if (len(tokens) > 1): raise BadCommandError, 'Too many arguments to "connect"' if (len(tokens) == 0): raise BadCommandError, 'Usage: .connect databasename' if (self.__db != None): try: self.__db.close() except db....