desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initialize a Message instance.'
def __init__(self, message=None):
if isinstance(message, email.message.Message): self._become_message(copy.deepcopy(message)) if isinstance(message, Message): message._explain_to(self) elif isinstance(message, str): self._become_message(email.message_from_string(message)) elif hasattr(message, 'read'): self._become_message(email.message_from_file(message)) elif (message is None): email.message.Message.__init__(self) else: raise TypeError(('Invalid message type: %s' % type(message)))
'Assume the non-format-specific state of message.'
def _become_message(self, message):
for name in ('_headers', '_unixfrom', '_payload', '_charset', 'preamble', 'epilogue', 'defects', '_default_type'): self.__dict__[name] = message.__dict__[name]
'Copy format-specific state to message insofar as possible.'
def _explain_to(self, message):
if isinstance(message, Message): return else: raise TypeError('Cannot convert to specified type')
'Initialize a MaildirMessage instance.'
def __init__(self, message=None):
self._subdir = 'new' self._info = '' self._date = time.time() Message.__init__(self, message)
'Return \'new\' or \'cur\'.'
def get_subdir(self):
return self._subdir
'Set subdir to \'new\' or \'cur\'.'
def set_subdir(self, subdir):
if ((subdir == 'new') or (subdir == 'cur')): self._subdir = subdir else: raise ValueError(("subdir must be 'new' or 'cur': %s" % subdir))
'Return as a string the flags that are set.'
def get_flags(self):
if self._info.startswith('2,'): return self._info[2:] else: return ''
'Set the given flags and unset all others.'
def set_flags(self, flags):
self._info = ('2,' + ''.join(sorted(flags)))
'Set the given flag(s) without changing others.'
def add_flag(self, flag):
self.set_flags(''.join((set(self.get_flags()) | set(flag))))
'Unset the given string flag(s) without changing others.'
def remove_flag(self, flag):
if (self.get_flags() != ''): self.set_flags(''.join((set(self.get_flags()) - set(flag))))
'Return delivery date of message, in seconds since the epoch.'
def get_date(self):
return self._date
'Set delivery date of message, in seconds since the epoch.'
def set_date(self, date):
try: self._date = float(date) except ValueError: raise TypeError(("can't convert to float: %s" % date))
'Get the message\'s "info" as a string.'
def get_info(self):
return self._info
'Set the message\'s "info" string.'
def set_info(self, info):
if isinstance(info, str): self._info = info else: raise TypeError(('info must be a string: %s' % type(info)))
'Copy Maildir-specific state to message insofar as possible.'
def _explain_to(self, message):
if isinstance(message, MaildirMessage): message.set_flags(self.get_flags()) message.set_subdir(self.get_subdir()) message.set_date(self.get_date()) elif isinstance(message, _mboxMMDFMessage): flags = set(self.get_flags()) if ('S' in flags): message.add_flag('R') if (self.get_subdir() == 'cur'): message.add_flag('O') if ('T' in flags): message.add_flag('D') if ('F' in flags): message.add_flag('F') if ('R' in flags): message.add_flag('A') message.set_from('MAILER-DAEMON', time.gmtime(self.get_date())) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if ('S' not in flags): message.add_sequence('unseen') if ('R' in flags): message.add_sequence('replied') if ('F' in flags): message.add_sequence('flagged') elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if ('S' not in flags): message.add_label('unseen') if ('T' in flags): message.add_label('deleted') if ('R' in flags): message.add_label('answered') if ('P' in flags): message.add_label('forwarded') elif isinstance(message, Message): pass else: raise TypeError(('Cannot convert to specified type: %s' % type(message)))
'Initialize an mboxMMDFMessage instance.'
def __init__(self, message=None):
self.set_from('MAILER-DAEMON', True) if isinstance(message, email.message.Message): unixfrom = message.get_unixfrom() if ((unixfrom is not None) and unixfrom.startswith('From ')): self.set_from(unixfrom[5:]) Message.__init__(self, message)
'Return contents of "From " line.'
def get_from(self):
return self._from
'Set "From " line, formatting and appending time_ if specified.'
def set_from(self, from_, time_=None):
if (time_ is not None): if (time_ is True): time_ = time.gmtime() from_ += (' ' + time.asctime(time_)) self._from = from_
'Return as a string the flags that are set.'
def get_flags(self):
return (self.get('Status', '') + self.get('X-Status', ''))
'Set the given flags and unset all others.'
def set_flags(self, flags):
flags = set(flags) (status_flags, xstatus_flags) = ('', '') for flag in ('R', 'O'): if (flag in flags): status_flags += flag flags.remove(flag) for flag in ('D', 'F', 'A'): if (flag in flags): xstatus_flags += flag flags.remove(flag) xstatus_flags += ''.join(sorted(flags)) try: self.replace_header('Status', status_flags) except KeyError: self.add_header('Status', status_flags) try: self.replace_header('X-Status', xstatus_flags) except KeyError: self.add_header('X-Status', xstatus_flags)
'Set the given flag(s) without changing others.'
def add_flag(self, flag):
self.set_flags(''.join((set(self.get_flags()) | set(flag))))
'Unset the given string flag(s) without changing others.'
def remove_flag(self, flag):
if (('Status' in self) or ('X-Status' in self)): self.set_flags(''.join((set(self.get_flags()) - set(flag))))
'Copy mbox- or MMDF-specific state to message insofar as possible.'
def _explain_to(self, message):
if isinstance(message, MaildirMessage): flags = set(self.get_flags()) if ('O' in flags): message.set_subdir('cur') if ('F' in flags): message.add_flag('F') if ('A' in flags): message.add_flag('R') if ('R' in flags): message.add_flag('S') if ('D' in flags): message.add_flag('T') del message['status'] del message['x-status'] maybe_date = ' '.join(self.get_from().split()[(-5):]) try: message.set_date(calendar.timegm(time.strptime(maybe_date, '%a %b %d %H:%M:%S %Y'))) except (ValueError, OverflowError): pass elif isinstance(message, _mboxMMDFMessage): message.set_flags(self.get_flags()) message.set_from(self.get_from()) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if ('R' not in flags): message.add_sequence('unseen') if ('A' in flags): message.add_sequence('replied') if ('F' in flags): message.add_sequence('flagged') del message['status'] del message['x-status'] elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if ('R' not in flags): message.add_label('unseen') if ('D' in flags): message.add_label('deleted') if ('A' in flags): message.add_label('answered') del message['status'] del message['x-status'] elif isinstance(message, Message): pass else: raise TypeError(('Cannot convert to specified type: %s' % type(message)))
'Initialize an MHMessage instance.'
def __init__(self, message=None):
self._sequences = [] Message.__init__(self, message)
'Return a list of sequences that include the message.'
def get_sequences(self):
return self._sequences[:]
'Set the list of sequences that include the message.'
def set_sequences(self, sequences):
self._sequences = list(sequences)
'Add sequence to list of sequences including the message.'
def add_sequence(self, sequence):
if isinstance(sequence, str): if (not (sequence in self._sequences)): self._sequences.append(sequence) else: raise TypeError(('sequence must be a string: %s' % type(sequence)))
'Remove sequence from the list of sequences including the message.'
def remove_sequence(self, sequence):
try: self._sequences.remove(sequence) except ValueError: pass
'Copy MH-specific state to message insofar as possible.'
def _explain_to(self, message):
if isinstance(message, MaildirMessage): sequences = set(self.get_sequences()) if ('unseen' in sequences): message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if ('flagged' in sequences): message.add_flag('F') if ('replied' in sequences): message.add_flag('R') elif isinstance(message, _mboxMMDFMessage): sequences = set(self.get_sequences()) if ('unseen' not in sequences): message.add_flag('RO') else: message.add_flag('O') if ('flagged' in sequences): message.add_flag('F') if ('replied' in sequences): message.add_flag('A') elif isinstance(message, MHMessage): for sequence in self.get_sequences(): message.add_sequence(sequence) elif isinstance(message, BabylMessage): sequences = set(self.get_sequences()) if ('unseen' in sequences): message.add_label('unseen') if ('replied' in sequences): message.add_label('answered') elif isinstance(message, Message): pass else: raise TypeError(('Cannot convert to specified type: %s' % type(message)))
'Initialize a BabylMessage instance.'
def __init__(self, message=None):
self._labels = [] self._visible = Message() Message.__init__(self, message)
'Return a list of labels on the message.'
def get_labels(self):
return self._labels[:]
'Set the list of labels on the message.'
def set_labels(self, labels):
self._labels = list(labels)
'Add label to list of labels on the message.'
def add_label(self, label):
if isinstance(label, str): if (label not in self._labels): self._labels.append(label) else: raise TypeError(('label must be a string: %s' % type(label)))
'Remove label from the list of labels on the message.'
def remove_label(self, label):
try: self._labels.remove(label) except ValueError: pass
'Return a Message representation of visible headers.'
def get_visible(self):
return Message(self._visible)
'Set the Message representation of visible headers.'
def set_visible(self, visible):
self._visible = Message(visible)
'Update and/or sensibly generate a set of visible headers.'
def update_visible(self):
for header in self._visible.keys(): if (header in self): self._visible.replace_header(header, self[header]) else: del self._visible[header] for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'): if ((header in self) and (header not in self._visible)): self._visible[header] = self[header]
'Copy Babyl-specific state to message insofar as possible.'
def _explain_to(self, message):
if isinstance(message, MaildirMessage): labels = set(self.get_labels()) if ('unseen' in labels): message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if (('forwarded' in labels) or ('resent' in labels)): message.add_flag('P') if ('answered' in labels): message.add_flag('R') if ('deleted' in labels): message.add_flag('T') elif isinstance(message, _mboxMMDFMessage): labels = set(self.get_labels()) if ('unseen' not in labels): message.add_flag('RO') else: message.add_flag('O') if ('deleted' in labels): message.add_flag('D') if ('answered' in labels): message.add_flag('A') elif isinstance(message, MHMessage): labels = set(self.get_labels()) if ('unseen' in labels): message.add_sequence('unseen') if ('answered' in labels): message.add_sequence('replied') elif isinstance(message, BabylMessage): message.set_visible(self.get_visible()) for label in self.get_labels(): message.add_label(label) elif isinstance(message, Message): pass else: raise TypeError(('Cannot convert to specified type: %s' % type(message)))
'Initialize a _ProxyFile.'
def __init__(self, f, pos=None):
self._file = f if (pos is None): self._pos = f.tell() else: self._pos = pos
'Read bytes.'
def read(self, size=None):
return self._read(size, self._file.read)
'Read a line.'
def readline(self, size=None):
return self._read(size, self._file.readline)
'Read multiple lines.'
def readlines(self, sizehint=None):
result = [] for line in self: result.append(line) if (sizehint is not None): sizehint -= len(line) if (sizehint <= 0): break return result
'Iterate over lines.'
def __iter__(self):
return iter(self.readline, '')
'Return the position.'
def tell(self):
return self._pos
'Change position.'
def seek(self, offset, whence=0):
if (whence == 1): self._file.seek(self._pos) self._file.seek(offset, whence) self._pos = self._file.tell()
'Close the file.'
def close(self):
if hasattr(self, '_file'): if hasattr(self._file, 'close'): self._file.close() del self._file
'Read size bytes using read_method.'
def _read(self, size, read_method):
if (size is None): size = (-1) self._file.seek(self._pos) result = read_method(size) self._pos = self._file.tell() return result
'Initialize a _PartialFile.'
def __init__(self, f, start=None, stop=None):
_ProxyFile.__init__(self, f, start) self._start = start self._stop = stop
'Return the position with respect to start.'
def tell(self):
return (_ProxyFile.tell(self) - self._start)
'Change position, possibly with respect to start or stop.'
def seek(self, offset, whence=0):
if (whence == 0): self._pos = self._start whence = 1 elif (whence == 2): self._pos = self._stop whence = 1 _ProxyFile.seek(self, offset, whence)
'Read size bytes using read_method, honoring start and stop.'
def _read(self, size, read_method):
remaining = (self._stop - self._pos) if (remaining <= 0): return '' if ((size is None) or (size < 0) or (size > remaining)): size = remaining return _ProxyFile._read(self, size, read_method)
'Return a parser object with index at \'index\''
def get_parser(self, index):
return HyperParser(self.editwin, index)
'test corner cases in the init method'
def test_init(self):
with self.assertRaises(ValueError) as ve: self.text.tag_add('console', '1.0', '1.end') p = self.get_parser('1.5') self.assertIn('precedes', str(ve.exception)) self.editwin.context_use_ps1 = False p = self.get_parser('end') self.assertEqual(p.rawtext, self.text.get('1.0', 'end')) self.text.insert('end', (self.text.get('1.0', 'end') * 4)) p = self.get_parser('54.5')
'Test pasting into text without a selection.'
def test_paste_text_no_selection(self):
text = self.text (tag, ans) = ('', 'onetwo\n') text.delete('1.0', 'end') text.insert('1.0', 'one', tag) text.event_generate('<<Paste>>') self.assertEqual(text.get('1.0', 'end'), ans)
'Test pasting into text with a selection.'
def test_paste_text_selection(self):
text = self.text (tag, ans) = ('sel', 'two\n') text.delete('1.0', 'end') text.insert('1.0', 'one', tag) text.event_generate('<<Paste>>') self.assertEqual(text.get('1.0', 'end'), ans)
'Test pasting into an entry without a selection.'
def test_paste_entry_no_selection(self):
entry = self.entry (end, ans) = (0, 'onetwo') entry.delete(0, 'end') entry.insert(0, 'one') entry.select_range(0, end) entry.event_generate('<<Paste>>') self.assertEqual(entry.get(), ans)
'Test pasting into an entry with a selection.'
def test_paste_entry_selection(self):
entry = self.entry (end, ans) = ('end', 'two') entry.delete(0, 'end') entry.insert(0, 'one') entry.select_range(0, end) entry.event_generate('<<Paste>>') self.assertEqual(entry.get(), ans)
'Test pasting into a spinbox without a selection.'
def test_paste_spin_no_selection(self):
spin = self.spin (end, ans) = (0, 'onetwo') spin.delete(0, 'end') spin.insert(0, 'one') spin.selection('range', 0, end) spin.event_generate('<<Paste>>') self.assertEqual(spin.get(), ans)
'Test pasting into a spinbox with a selection.'
def test_paste_spin_selection(self):
spin = self.spin (end, ans) = ('end', 'two') spin.delete(0, 'end') spin.insert(0, 'one') spin.selection('range', 0, end) spin.event_generate('<<Paste>>') self.assertEqual(spin.get(), ans)
'Test ParenMatch with \'expression\' style.'
def test_paren_expression(self):
text = self.text pm = ParenMatch(self.editwin) pm.set_style('expression') text.insert('insert', 'def foobar(a, b') pm.flash_paren_event('event') self.assertIn('<<parenmatch-check-restore>>', text.event_info()) self.assertTupleEqual(text.tag_prevrange('paren', 'end'), ('1.10', '1.15')) text.insert('insert', ')') pm.restore_event() self.assertNotIn('<<parenmatch-check-restore>>', text.event_info()) self.assertEqual(text.tag_prevrange('paren', 'end'), ()) pm.paren_closed_event('event') self.assertTupleEqual(text.tag_prevrange('paren', 'end'), ('1.10', '1.16'))
'Test ParenMatch with \'default\' style.'
def test_paren_default(self):
text = self.text pm = ParenMatch(self.editwin) pm.set_style('default') text.insert('insert', 'def foobar(a, b') pm.flash_paren_event('event') self.assertIn('<<parenmatch-check-restore>>', text.event_info()) self.assertTupleEqual(text.tag_prevrange('paren', 'end'), ('1.10', '1.11')) text.insert('insert', ')') pm.restore_event() self.assertNotIn('<<parenmatch-check-restore>>', text.event_info()) self.assertEqual(text.tag_prevrange('paren', 'end'), ())
'Test corner cases in flash_paren_event and paren_closed_event. These cases force conditional expression and alternate paths.'
def test_paren_corner(self):
text = self.text pm = ParenMatch(self.editwin) text.insert('insert', '# this is a commen)') self.assertIsNone(pm.paren_closed_event('event')) text.insert('insert', '\ndef') self.assertIsNone(pm.flash_paren_event('event')) self.assertIsNone(pm.paren_closed_event('event')) text.insert('insert', ' a, *arg)') self.assertIsNone(pm.paren_closed_event('event'))
'Create event with attributes needed for test'
def __init__(self, **kwds):
self.__dict__.update(kwds)
'Initialize mock, non-gui, text-only Text widget. At present, all args are ignored. Almost all affect visual behavior. There are just a few Text-only options that affect text behavior.'
def __init__(self, master=None, cnf={}, **kw):
self.data = ['', '\n']
'Return string version of index decoded according to current text.'
def index(self, index):
return ('%s.%s' % self._decode(index, endflag=1))
'Return a (line, char) tuple of int indexes into self.data. This implements .index without converting the result back to a string. The result is contrained by the number of lines and linelengths of self.data. For many indexes, the result is initially (1, 0). The input index may have any of several possible forms: * line.char float: converted to \'line.char\' string; * \'line.char\' string, where line and char are decimal integers; * \'line.char lineend\', where lineend=\'lineend\' (and char is ignored); * \'line.end\', where end=\'end\' (same as above); * \'insert\', the positions before terminal * \'end\', whose meaning depends on the endflag passed to ._endex. * \'sel.first\' or \'sel.last\', where sel is a tag -- not implemented.'
def _decode(self, index, endflag=0):
if isinstance(index, (float, bytes)): index = str(index) try: index = index.lower() except AttributeError: raise TclError(('bad text index "%s"' % index)) lastline = (len(self.data) - 1) if (index == 'insert'): return (lastline, (len(self.data[lastline]) - 1)) elif (index == 'end'): return self._endex(endflag) (line, char) = index.split('.') line = int(line) if (line < 1): return (1, 0) elif (line > lastline): return self._endex(endflag) linelength = (len(self.data[line]) - 1) if (char.endswith(' lineend') or (char == 'end')): return (line, linelength) char = int(char) if (char < 0): char = 0 elif (char > linelength): char = linelength return (line, char)
'Return position for \'end\' or line overflow corresponding to endflag. -1: position before terminal ; for .insert(), .delete 0: position after terminal ; for .get, .delete index 1 1: same viewed as beginning of non-existent next line (for .index)'
def _endex(self, endflag):
n = len(self.data) if (endflag == 1): return (n, 0) else: n -= 1 return (n, (len(self.data[n]) + endflag))
'Insert chars before the character at index.'
def insert(self, index, chars):
if (not chars): return chars = chars.splitlines(True) if (chars[(-1)][(-1)] == '\n'): chars.append('') (line, char) = self._decode(index, (-1)) before = self.data[line][:char] after = self.data[line][char:] self.data[line] = (before + chars[0]) self.data[(line + 1):(line + 1)] = chars[1:] self.data[((line + len(chars)) - 1)] += after
'Return slice from index1 to index2 (default is \'index1+1\').'
def get(self, index1, index2=None):
(startline, startchar) = self._decode(index1) if (index2 is None): (endline, endchar) = (startline, (startchar + 1)) else: (endline, endchar) = self._decode(index2) if (startline == endline): return self.data[startline][startchar:endchar] else: lines = [self.data[startline][startchar:]] for i in range((startline + 1), endline): lines.append(self.data[i]) lines.append(self.data[endline][:endchar]) return ''.join(lines)
'Delete slice from index1 to index2 (default is \'index1+1\'). Adjust default index2 (\'index+1) for line ends. Do not delete the terminal at the very end of self.data ([-1][-1]).'
def delete(self, index1, index2=None):
(startline, startchar) = self._decode(index1, (-1)) if (index2 is None): if (startchar < (len(self.data[startline]) - 1)): (endline, endchar) = (startline, (startchar + 1)) elif (startline < (len(self.data) - 1)): (endline, endchar) = ((startline + 1), 0) else: return else: (endline, endchar) = self._decode(index2, (-1)) if ((startline == endline) and (startchar < endchar)): self.data[startline] = (self.data[startline][:startchar] + self.data[startline][endchar:]) elif (startline < endline): self.data[startline] = (self.data[startline][:startchar] + self.data[endline][endchar:]) startline += 1 for i in range(startline, (endline + 1)): del self.data[startline]
'Set mark *name* before the character at index.'
def mark_set(self, name, index):
pass
'Remove tag tagName from all characters between index1 and index2.'
def tag_remove(self, tagName, index1, index2=None):
pass
'Scroll screen to make the character at INDEX is visible.'
def see(self, index):
pass
'Bind to this widget at event sequence a call to function func.'
def bind(sequence=None, func=None, add=None):
pass
'Return a (user, account, password) tuple for given host.'
def authenticators(self, host):
if (host in self.hosts): return self.hosts[host] elif ('default' in self.hosts): return self.hosts['default'] else: return None
'Dump the class data in the format of a .netrc file.'
def __repr__(self):
rep = '' for host in self.hosts.keys(): attrs = self.hosts[host] rep = (((((rep + 'machine ') + host) + '\n DCTB login ') + repr(attrs[0])) + '\n') if attrs[1]: rep = ((rep + 'account ') + repr(attrs[1])) rep = (((rep + ' DCTB password ') + repr(attrs[2])) + '\n') for macro in self.macros.keys(): rep = (((rep + 'macdef ') + macro) + '\n') for line in self.macros[macro]: rep = (rep + line) rep = (rep + '\n') return rep
'Constructor. See class doc string.'
def __init__(self, stmt='pass', setup='pass', timer=default_timer):
self.timer = timer ns = {} if isinstance(stmt, basestring): if isinstance(setup, basestring): compile(setup, dummy_src_name, 'exec') compile(((setup + '\n') + stmt), dummy_src_name, 'exec') else: compile(stmt, dummy_src_name, 'exec') stmt = reindent(stmt, 8) if isinstance(setup, basestring): setup = reindent(setup, 4) src = (template % {'stmt': stmt, 'setup': setup, 'init': ''}) elif hasattr(setup, '__call__'): src = (template % {'stmt': stmt, 'setup': '_setup()', 'init': ', _setup=_setup'}) ns['_setup'] = setup else: raise ValueError('setup is neither a string nor callable') self.src = src code = compile(src, dummy_src_name, 'exec') exec code in globals(), ns self.inner = ns['inner'] elif hasattr(stmt, '__call__'): self.src = None if isinstance(setup, basestring): _setup = setup def setup(): exec _setup in globals(), ns elif (not hasattr(setup, '__call__')): raise ValueError('setup is neither a string nor callable') self.inner = _template_func(setup, stmt) else: raise ValueError('stmt is neither a string nor callable')
'Helper to print a traceback from the timed code. Typical use: t = Timer(...) # outside the try/except try: t.timeit(...) # or t.repeat(...) except: t.print_exc() The advantage over the standard traceback is that source lines in the compiled template will be displayed. The optional file argument directs where the traceback is sent; it defaults to sys.stderr.'
def print_exc(self, file=None):
import linecache, traceback if (self.src is not None): linecache.cache[dummy_src_name] = (len(self.src), None, self.src.split('\n'), dummy_src_name) traceback.print_exc(file=file)
'Time \'number\' executions of the main statement. To be precise, this executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, as a float measured in seconds. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor.'
def timeit(self, number=default_number):
if itertools: it = itertools.repeat(None, number) else: it = ([None] * number) gcold = gc.isenabled() gc.disable() try: timing = self.inner(it, self.timer) finally: if gcold: gc.enable() return timing
'Call timeit() a few times. This is a convenience function that calls the timeit() repeatedly, returning a list of results. The first argument specifies how many times to call timeit(), defaulting to 3; the second argument specifies the timer argument, defaulting to one million. Note: it\'s tempting to calculate mean and standard deviation from the result vector and report these. However, this is not very useful. In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python\'s speed, but by other processes interfering with your timing accuracy. So the min() of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics.'
def repeat(self, repeat=default_repeat, number=default_number):
r = [] for i in range(repeat): t = self.timeit(number) r.append(t) return r
'Create a decimal point instance. >>> Decimal(\'3.14\') # string input Decimal(\'3.14\') >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal(\'3.14\') >>> Decimal(314) # int or long Decimal(\'314\') >>> Decimal(Decimal(314)) # another decimal instance Decimal(\'314\') >>> Decimal(\' 3.14 \n\') # leading and trailing whitespace okay Decimal(\'3.14\')'
def __new__(cls, value='0', context=None):
self = object.__new__(cls) import sys if (sys.platform == 'cli'): import System if isinstance(value, System.Decimal): value = str(value) if isinstance(value, basestring): m = _parser(value.strip()) if (m is None): if (context is None): context = getcontext() return context._raise_error(ConversionSyntax, ('Invalid literal for Decimal: %r' % value)) if (m.group('sign') == '-'): self._sign = 1 else: self._sign = 0 intpart = m.group('int') if (intpart is not None): fracpart = (m.group('frac') or '') exp = int((m.group('exp') or '0')) self._int = str(int((intpart + fracpart))) self._exp = (exp - len(fracpart)) self._is_special = False else: diag = m.group('diag') if (diag is not None): self._int = str(int((diag or '0'))).lstrip('0') if m.group('signal'): self._exp = 'N' else: self._exp = 'n' else: self._int = '0' self._exp = 'F' self._is_special = True return self if isinstance(value, (int, long)): if (value >= 0): self._sign = 0 else: self._sign = 1 self._exp = 0 self._int = str(abs(value)) self._is_special = False return self if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self if isinstance(value, _WorkRep): self._sign = value.sign self._int = str(value.int) self._exp = int(value.exp) self._is_special = False return self if isinstance(value, (list, tuple)): if (len(value) != 3): raise ValueError('Invalid tuple size in creation of Decimal from list or tuple. The list or tuple should have exactly three elements.') if (not (isinstance(value[0], (int, long)) and (value[0] in (0, 1)))): raise ValueError('Invalid sign. The first value in the tuple should be an integer; either 0 for a positive number or 1 for a negative number.') self._sign = value[0] if (value[2] == 'F'): self._int = '0' self._exp = value[2] self._is_special = True else: digits = [] for digit in value[1]: if (isinstance(digit, (int, long)) and (0 <= digit <= 9)): if (digits or (digit != 0)): digits.append(digit) else: raise ValueError('The second value in the tuple must be composed of integers in the range 0 through 9.') if (value[2] in ('n', 'N')): self._int = ''.join(map(str, digits)) self._exp = value[2] self._is_special = True elif isinstance(value[2], (int, long)): self._int = ''.join(map(str, (digits or [0]))) self._exp = value[2] self._is_special = False else: raise ValueError("The third value in the tuple must be an integer, or one of the strings 'F', 'n', 'N'.") return self if isinstance(value, float): value = Decimal.from_float(value) self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self raise TypeError(('Cannot convert %r to Decimal' % value))
'Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal(\'0.1\'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0.1000000000000000055511151231257827021181583404541015625. >>> Decimal.from_float(0.1) Decimal(\'0.1000000000000000055511151231257827021181583404541015625\') >>> Decimal.from_float(float(\'nan\')) Decimal(\'NaN\') >>> Decimal.from_float(float(\'inf\')) Decimal(\'Infinity\') >>> Decimal.from_float(-float(\'inf\')) Decimal(\'-Infinity\') >>> Decimal.from_float(-0.0) Decimal(\'-0\')'
def from_float(cls, f):
if isinstance(f, (int, long)): return cls(f) if (_math.isinf(f) or _math.isnan(f)): return cls(repr(f)) if (_math.copysign(1.0, f) == 1.0): sign = 0 else: sign = 1 (n, d) = abs(f).as_integer_ratio() k = (d.bit_length() - 1) result = _dec_from_triple(sign, str((n * (5 ** k))), (- k)) if (cls is Decimal): return result else: return cls(result)
'Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN'
def _isnan(self):
if self._is_special: exp = self._exp if (exp == 'n'): return 1 elif (exp == 'N'): return 2 return 0
'Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF'
def _isinfinity(self):
if (self._exp == 'F'): if self._sign: return (-1) return 1 return 0
'Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations.'
def _check_nans(self, other=None, context=None):
self_is_nan = self._isnan() if (other is None): other_is_nan = False else: other_is_nan = other._isnan() if (self_is_nan or other_is_nan): if (context is None): context = getcontext() if (self_is_nan == 2): return context._raise_error(InvalidOperation, 'sNaN', self) if (other_is_nan == 2): return context._raise_error(InvalidOperation, 'sNaN', other) if self_is_nan: return self._fix_nan(context) return other._fix_nan(context) return 0
'Version of _check_nans used for the signaling comparisons compare_signal, __le__, __lt__, __ge__, __gt__. Signal InvalidOperation if either self or other is a (quiet or signaling) NaN. Signaling NaNs take precedence over quiet NaNs. Return 0 if neither operand is a NaN.'
def _compare_check_nans(self, other, context):
if (context is None): context = getcontext() if (self._is_special or other._is_special): if self.is_snan(): return context._raise_error(InvalidOperation, 'comparison involving sNaN', self) elif other.is_snan(): return context._raise_error(InvalidOperation, 'comparison involving sNaN', other) elif self.is_qnan(): return context._raise_error(InvalidOperation, 'comparison involving NaN', self) elif other.is_qnan(): return context._raise_error(InvalidOperation, 'comparison involving NaN', other) return 0
'Return True if self is nonzero; otherwise return False. NaNs and infinities are considered nonzero.'
def __nonzero__(self):
return (self._is_special or (self._int != '0'))
'Compare the two non-NaN decimal instances self and other. Returns -1 if self < other, 0 if self == other and 1 if self > other. This routine is for internal use only.'
def _cmp(self, other):
if (self._is_special or other._is_special): self_inf = self._isinfinity() other_inf = other._isinfinity() if (self_inf == other_inf): return 0 elif (self_inf < other_inf): return (-1) else: return 1 if (not self): if (not other): return 0 else: return (- ((-1) ** other._sign)) if (not other): return ((-1) ** self._sign) if (other._sign < self._sign): return (-1) if (self._sign < other._sign): return 1 self_adjusted = self.adjusted() other_adjusted = other.adjusted() if (self_adjusted == other_adjusted): self_padded = (self._int + ('0' * (self._exp - other._exp))) other_padded = (other._int + ('0' * (other._exp - self._exp))) if (self_padded == other_padded): return 0 elif (self_padded < other_padded): return (- ((-1) ** self._sign)) else: return ((-1) ** self._sign) elif (self_adjusted > other_adjusted): return ((-1) ** self._sign) else: return (- ((-1) ** self._sign))
'Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances.'
def compare(self, other, context=None):
other = _convert_other(other, raiseit=True) if (self._is_special or (other and other._is_special)): ans = self._check_nans(other, context) if ans: return ans return Decimal(self._cmp(other))
'x.__hash__() <==> hash(x)'
def __hash__(self):
if self._is_special: if self.is_snan(): raise TypeError('Cannot hash a signaling NaN value.') elif self.is_nan(): return 0 elif self._sign: return (-271828) else: return 314159 self_as_float = float(self) if (Decimal.from_float(self_as_float) == self): return hash(self_as_float) if self._isinteger(): op = _WorkRep(self.to_integral_value()) return hash(((((-1) ** op.sign) * op.int) * pow(10, op.exp, ((2 ** 64) - 1)))) return hash((self._sign, (self._exp + len(self._int)), self._int.rstrip('0')))
'Represents the number as a triple tuple. To show the internals exactly as they are.'
def as_tuple(self):
return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
'Represents the number as an instance of Decimal.'
def __repr__(self):
return ("Decimal('%s')" % str(self))
'Return string representation of the number in scientific notation. Captures all of the information in the underlying representation.'
def __str__(self, eng=False, context=None):
sign = ['', '-'][self._sign] if self._is_special: if (self._exp == 'F'): return (sign + 'Infinity') elif (self._exp == 'n'): return ((sign + 'NaN') + self._int) else: return ((sign + 'sNaN') + self._int) leftdigits = (self._exp + len(self._int)) if ((self._exp <= 0) and (leftdigits > (-6))): dotplace = leftdigits elif (not eng): dotplace = 1 elif (self._int == '0'): dotplace = (((leftdigits + 1) % 3) - 1) else: dotplace = (((leftdigits - 1) % 3) + 1) if (dotplace <= 0): intpart = '0' fracpart = (('.' + ('0' * (- dotplace))) + self._int) elif (dotplace >= len(self._int)): intpart = (self._int + ('0' * (dotplace - len(self._int)))) fracpart = '' else: intpart = self._int[:dotplace] fracpart = ('.' + self._int[dotplace:]) if (leftdigits == dotplace): exp = '' else: if (context is None): context = getcontext() exp = (['e', 'E'][context.capitals] + ('%+d' % (leftdigits - dotplace))) return (((sign + intpart) + fracpart) + exp)
'Convert to engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. Same rules for when in exponential and when as a value as in __str__.'
def to_eng_string(self, context=None):
return self.__str__(eng=True, context=context)
'Returns a copy with the sign switched. Rounds, if it has reason.'
def __neg__(self, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if (context is None): context = getcontext() if ((not self) and (context.rounding != ROUND_FLOOR)): ans = self.copy_abs() else: ans = self.copy_negate() return ans._fix(context)
'Returns a copy, unless it is a sNaN. Rounds the number (if more than precision digits)'
def __pos__(self, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if (context is None): context = getcontext() if ((not self) and (context.rounding != ROUND_FLOOR)): ans = self.copy_abs() else: ans = Decimal(self) return ans._fix(context)
'Returns the absolute value of self. If the keyword argument \'round\' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs().'
def __abs__(self, round=True, context=None):
if (not round): return self.copy_abs() if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans
'Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors.'
def __add__(self, other, context=None):
other = _convert_other(other) if (other is NotImplemented): return other if (context is None): context = getcontext() if (self._is_special or other._is_special): ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if ((self._sign != other._sign) and other._isinfinity()): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other) exp = min(self._exp, other._exp) negativezero = 0 if ((context.rounding == ROUND_FLOOR) and (self._sign != other._sign)): negativezero = 1 if ((not self) and (not other)): sign = min(self._sign, other._sign) if negativezero: sign = 1 ans = _dec_from_triple(sign, '0', exp) ans = ans._fix(context) return ans if (not self): exp = max(exp, ((other._exp - context.prec) - 1)) ans = other._rescale(exp, context.rounding) ans = ans._fix(context) return ans if (not other): exp = max(exp, ((self._exp - context.prec) - 1)) ans = self._rescale(exp, context.rounding) ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) (op1, op2) = _normalize(op1, op2, context.prec) result = _WorkRep() if (op1.sign != op2.sign): if (op1.int == op2.int): ans = _dec_from_triple(negativezero, '0', exp) ans = ans._fix(context) return ans if (op1.int < op2.int): (op1, op2) = (op2, op1) if (op1.sign == 1): result.sign = 1 (op1.sign, op2.sign) = (op2.sign, op1.sign) else: result.sign = 0 elif (op1.sign == 1): result.sign = 1 (op1.sign, op2.sign) = (0, 0) else: result.sign = 0 if (op2.sign == 0): result.int = (op1.int + op2.int) else: result.int = (op1.int - op2.int) result.exp = op1.exp ans = Decimal(result) ans = ans._fix(context) return ans
'Return self - other'
def __sub__(self, other, context=None):
other = _convert_other(other) if (other is NotImplemented): return other if (self._is_special or other._is_special): ans = self._check_nans(other, context=context) if ans: return ans return self.__add__(other.copy_negate(), context=context)
'Return other - self'
def __rsub__(self, other, context=None):
other = _convert_other(other) if (other is NotImplemented): return other return other.__sub__(self, context=context)