desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Update this hashing object with the string msg.'
| def update(self, msg):
| self.inner.update(msg)
|
'Return a separate copy of this hashing object.
An update to this copy won\'t affect the original object.'
| def copy(self):
| other = self.__class__(_secret_backdoor_key)
other.digest_cons = self.digest_cons
other.digest_size = self.digest_size
other.inner = self.inner.copy()
other.outer = self.outer.copy()
return other
|
'Return a hash object for the current state.
To be used only internally with digest() and hexdigest().'
| def _current(self):
| h = self.outer.copy()
h.update(self.inner.digest())
return h
|
'Return the hash value of this hashing object.
This returns a string containing 8-bit data. The object is
not altered in any way by this function; you can continue
updating the object after calling this function.'
| def digest(self):
| h = self._current()
return h.digest()
|
'Like digest(), but returns a string of hexadecimal digits instead.'
| def hexdigest(self):
| h = self._current()
return h.hexdigest()
|
'Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
not have a method with the specified name.'
| def __init__(self, methodName='runTest'):
| self._testMethodName = methodName
self._resultForDoCleanups = None
try:
testMethod = getattr(self, methodName)
except AttributeError:
raise ValueError(('no such test method in %s: %s' % (self.__class__, methodName)))
self._testMethodDoc = testMethod.__doc__
self... |
'Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function... | def addTypeEqualityFunc(self, typeobj, function):
| self._type_equality_funcs[typeobj] = function
|
'Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).'
| def addCleanup(self, function, *args, **kwargs):
| self._cleanups.append((function, args, kwargs))
|
'Hook method for setting up the test fixture before exercising it.'
| def setUp(self):
| pass
|
'Hook method for deconstructing the test fixture after testing it.'
| def tearDown(self):
| pass
|
'Hook method for setting up class fixture before running tests in the class.'
| @classmethod
def setUpClass(cls):
| pass
|
'Hook method for deconstructing the class fixture after running all tests in the class.'
| @classmethod
def tearDownClass(cls):
| pass
|
'Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of
the specified test method\'s docstring.'
| def shortDescription(self):
| doc = self._testMethodDoc
return ((doc and doc.split('\n')[0].strip()) or None)
|
'Execute all cleanup functions. Normally called for you after
tearDown.'
| def doCleanups(self):
| result = self._resultForDoCleanups
ok = True
while self._cleanups:
(function, args, kwargs) = self._cleanups.pop((-1))
try:
function(*args, **kwargs)
except KeyboardInterrupt:
raise
except:
ok = False
result.addError(self, sys.e... |
'Run the test without collecting errors in a TestResult'
| def debug(self):
| self.setUp()
getattr(self, self._testMethodName)()
self.tearDown()
while self._cleanups:
(function, args, kwargs) = self._cleanups.pop((-1))
function(*args, **kwargs)
|
'Skip this test.'
| def skipTest(self, reason):
| raise SkipTest(reason)
|
'Fail immediately, with the given message.'
| def fail(self, msg=None):
| raise self.failureException(msg)
|
'Check that the expression is false.'
| def assertFalse(self, expr, msg=None):
| if expr:
msg = self._formatMessage(msg, ('%s is not false' % safe_repr(expr)))
raise self.failureException(msg)
|
'Check that the expression is true.'
| def assertTrue(self, expr, msg=None):
| if (not expr):
msg = self._formatMessage(msg, ('%s is not true' % safe_repr(expr)))
raise self.failureException(msg)
|
'Honour the longMessage attribute when generating failure messages.
If longMessage is False this means:
* Use only an explicit message if it is provided
* Otherwise use the standard message for the assert
If longMessage is True:
* Use the standard message
* If an explicit message is provided, plus \' : \' and the expli... | def _formatMessage(self, msg, standardMsg):
| if (not self.longMessage):
return (msg or standardMsg)
else:
if (msg is None):
return standardMsg
try:
return ('%s : %s' % (standardMsg, msg))
except UnicodeDecodeError:
return ('%s : %s' % (safe_repr(standardMsg), safe_repr(msg)))
... |
'Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with callab... | def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
| context = _AssertRaisesContext(excClass, self)
if (callableObj is None):
return context
else:
with context:
callableObj(*args, **kwargs)
return
|
'Get a detailed comparison function for the types of the two args.
Returns: A callable accepting (first, second, msg=None) that will
raise a failure exception if first != second with a useful human
readable error message for those types.'
| def _getAssertEqualityFunc(self, first, second):
| if (type(first) is type(second)):
asserter = self._type_equality_funcs.get(type(first))
if (asserter is not None):
return asserter
return self._baseAssertEqual
|
'The default assertEqual implementation, not type specific.'
| def _baseAssertEqual(self, first, second, msg=None):
| if (not (first == second)):
standardMsg = ('%s != %s' % (safe_repr(first), safe_repr(second)))
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
|
'Fail if the two objects are unequal as determined by the \'==\'
operator.'
| def assertEqual(self, first, second, msg=None):
| assertion_func = self._getAssertEqualityFunc(first, second)
assertion_func(first, second, msg=msg)
|
'Fail if the two objects are equal as determined by the \'==\'
operator.'
| def assertNotEqual(self, first, second, msg=None):
| if (not (first != second)):
msg = self._formatMessage(msg, ('%s == %s' % (safe_repr(first), safe_repr(second))))
raise self.failureException(msg)
|
'Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
between the two objects is more than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (meas... | def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
| if (first == second):
return
else:
if ((delta is not None) and (places is not None)):
raise TypeError('specify delta or places not both')
if (delta is not None):
if (abs((first - second)) <= delta):
return
standardMsg = (... |
'Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measur... | def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
| if ((delta is not None) and (places is not None)):
raise TypeError('specify delta or places not both')
if (delta is not None):
if ((not (first == second)) and (abs((first - second)) > delta)):
return
standardMsg = ('%s == %s within %s delta' % (s... |
'An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype... | def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
| if (seq_type is not None):
seq_type_name = seq_type.__name__
if (not isinstance(seq1, seq_type)):
raise self.failureException(('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1))))
if (not isinstance(seq2, seq_type)):
raise self.failu... |
'A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.'
| def assertListEqual(self, list1, list2, msg=None):
| self.assertSequenceEqual(list1, list2, msg, seq_type=list)
|
'A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.'
| def assertTupleEqual(self, tuple1, tuple2, msg=None):
| self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
|
'A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
differ... | def assertSetEqual(self, set1, set2, msg=None):
| try:
difference1 = set1.difference(set2)
except TypeError as e:
self.fail(('invalid type when attempting set difference: %s' % e))
except AttributeError as e:
self.fail(('first argument does not support set difference: %s' % e))
try:
... |
'Just like self.assertTrue(a in b), but with a nicer default message.'
| def assertIn(self, member, container, msg=None):
| if (member not in container):
standardMsg = ('%s not found in %s' % (safe_repr(member), safe_repr(container)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a not in b), but with a nicer default message.'
| def assertNotIn(self, member, container, msg=None):
| if (member in container):
standardMsg = ('%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a is b), but with a nicer default message.'
| def assertIs(self, expr1, expr2, msg=None):
| if (expr1 is not expr2):
standardMsg = ('%s is not %s' % (safe_repr(expr1), safe_repr(expr2)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a is not b), but with a nicer default message.'
| def assertIsNot(self, expr1, expr2, msg=None):
| if (expr1 is expr2):
standardMsg = ('unexpectedly identical: %s' % (safe_repr(expr1),))
self.fail(self._formatMessage(msg, standardMsg))
|
'Checks whether actual is a superset of expected.'
| def assertDictContainsSubset(self, expected, actual, msg=None):
| missing = []
mismatched = []
for (key, value) in expected.iteritems():
if (key not in actual):
missing.append(key)
elif (value != actual[key]):
mismatched.append(('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[key]))))... |
'An unordered sequence specific comparison. It asserts that
actual_seq and expected_seq have the same element counts.
Equivalent to::
self.assertEqual(Counter(iter(actual_seq)),
Counter(iter(expected_seq)))
Asserts that each element has the same count in both sequences.
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.... | def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
| (first_seq, second_seq) = (list(actual_seq), list(expected_seq))
with warnings.catch_warnings():
if sys.py3kwarning:
for _msg in ['(code|dict|type) inequality comparisons', 'builtin_function_or_method order comparisons', 'comparing unequal types']:
warnings.... |
'Assert that two multi-line strings are equal.'
| def assertMultiLineEqual(self, first, second, msg=None):
| self.assertIsInstance(first, basestring, 'First argument is not a string')
self.assertIsInstance(second, basestring, 'Second argument is not a string')
if (first != second):
if ((len(first) > self._diffThreshold) or (len(second) > self._diffThreshold)):
self... |
'Just like self.assertTrue(a < b), but with a nicer default message.'
| def assertLess(self, a, b, msg=None):
| if (not (a < b)):
standardMsg = ('%s not less than %s' % (safe_repr(a), safe_repr(b)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a <= b), but with a nicer default message.'
| def assertLessEqual(self, a, b, msg=None):
| if (not (a <= b)):
standardMsg = ('%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a > b), but with a nicer default message.'
| def assertGreater(self, a, b, msg=None):
| if (not (a > b)):
standardMsg = ('%s not greater than %s' % (safe_repr(a), safe_repr(b)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Just like self.assertTrue(a >= b), but with a nicer default message.'
| def assertGreaterEqual(self, a, b, msg=None):
| if (not (a >= b)):
standardMsg = ('%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Same as self.assertTrue(obj is None), with a nicer default message.'
| def assertIsNone(self, obj, msg=None):
| if (obj is not None):
standardMsg = ('%s is not None' % (safe_repr(obj),))
self.fail(self._formatMessage(msg, standardMsg))
return
|
'Included for symmetry with assertIsNone.'
| def assertIsNotNone(self, obj, msg=None):
| if (obj is None):
standardMsg = 'unexpectedly None'
self.fail(self._formatMessage(msg, standardMsg))
return
|
'Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.'
| def assertIsInstance(self, obj, cls, msg=None):
| if (not isinstance(obj, cls)):
standardMsg = ('%s is not an instance of %r' % (safe_repr(obj), cls))
self.fail(self._formatMessage(msg, standardMsg))
|
'Included for symmetry with assertIsInstance.'
| def assertNotIsInstance(self, obj, cls, msg=None):
| if isinstance(obj, cls):
standardMsg = ('%s is an instance of %r' % (safe_repr(obj), cls))
self.fail(self._formatMessage(msg, standardMsg))
|
'Asserts that the message in a raised exception matches a regexp.
Args:
expected_exception: Exception class expected to be raised.
expected_regexp: Regexp (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.'
| def assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs):
| context = _AssertRaisesContext(expected_exception, self, expected_regexp)
if (callable_obj is None):
return context
else:
with context:
callable_obj(*args, **kwargs)
return
|
'Fail the test unless the text matches the regular expression.'
| def assertRegexpMatches(self, text, expected_regexp, msg=None):
| if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if (not expected_regexp.search(text)):
msg = (msg or "Regexp didn't match")
msg = ('%s: %r not found in %r' % (msg, expected_regexp.pattern, text))
raise self.failureExc... |
'Fail the test if the text matches the regular expression.'
| def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
| if isinstance(unexpected_regexp, basestring):
unexpected_regexp = re.compile(unexpected_regexp)
match = unexpected_regexp.search(text)
if match:
msg = (msg or 'Regexp matched')
msg = ('%s: %r matches %r in %r' % (msg, text[match.start():match.end()], unexpected_rege... |
'Called by TestRunner after test run'
| def printErrors(self):
| pass
|
'Called when the given test is about to be run'
| def startTest(self, test):
| self.testsRun += 1
self._mirrorOutput = False
self._setupStdout()
|
'Called once before any tests are executed.
See startTest for a method called before each test.'
| def startTestRun(self):
| pass
|
'Called when the given test has been run'
| def stopTest(self, test):
| self._restoreStdout()
self._mirrorOutput = False
|
'Called once after all tests are executed.
See stopTest for a method called after each test.'
| def stopTestRun(self):
| pass
|
'Called when an error has occurred. \'err\' is a tuple of values as
returned by sys.exc_info().'
| @failfast
def addError(self, test, err):
| self.errors.append((test, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
|
'Called when an error has occurred. \'err\' is a tuple of values as
returned by sys.exc_info().'
| @failfast
def addFailure(self, test, err):
| self.failures.append((test, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
|
'Called when a test has completed successfully'
| def addSuccess(self, test):
| pass
|
'Called when a test is skipped.'
| def addSkip(self, test, reason):
| self.skipped.append((test, reason))
|
'Called when an expected failure/error occured.'
| def addExpectedFailure(self, test, err):
| self.expectedFailures.append((test, self._exc_info_to_string(err, test)))
|
'Called when a test was expected to fail, but succeed.'
| @failfast
def addUnexpectedSuccess(self, test):
| self.unexpectedSuccesses.append(test)
|
'Tells whether or not this result was a success'
| def wasSuccessful(self):
| return (len(self.failures) == len(self.errors) == 0)
|
'Indicates that the tests should be aborted'
| def stop(self):
| self.shouldStop = True
|
'Converts a sys.exc_info()-style tuple of values into a string.'
| def _exc_info_to_string(self, err, test):
| (exctype, value, tb) = err
while (tb and self._is_relevant_tb_level(tb)):
tb = tb.tb_next
if (exctype is test.failureException):
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format... |
'Run the given test case or test suite.'
| def run(self, test):
| result = self._makeResult()
registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if (startTestRun is not None):
startTestRun()
try:
test(result)
finally:
... |
'Return a suite of all tests cases contained in testCaseClass'
| def loadTestsFromTestCase(self, testCaseClass):
| if issubclass(testCaseClass, suite.TestSuite):
raise TypeError('Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?')
testCaseNames = self.getTestCaseNames(testCaseClass)
if ((not testCaseNames) and hasattr(testCaseClass... |
'Return a suite of all tests cases contained in the given module'
| def loadTestsFromModule(self, module, use_load_tests=True):
| tests = []
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, type) and issubclass(obj, case.TestCase)):
tests.append(self.loadTestsFromTestCase(obj))
load_tests = getattr(module, 'load_tests', None)
tests = self.suiteClass(tests)
if (use_load_tests ... |
'Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.'
| def loadTestsFromName(self, name, module=None):
| parts = name.split('.')
if (module is None):
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[(-1)]
if (not parts_copy):
... |
'Return a suite of all tests cases found using the given sequence
of string specifiers. See \'loadTestsFromName()\'.'
| def loadTestsFromNames(self, names, module=None):
| suites = [self.loadTestsFromName(name, module) for name in names]
return self.suiteClass(suites)
|
'Return a sorted sequence of method names found within testCaseClass'
| def getTestCaseNames(self, testCaseClass):
| def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
return (attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__'))
testFnNames = filter(isTestMethod, dir(testCaseClass))
if self.sortTestMethodsUsing:
testFnNames.sort(key=_Cmp... |
'Find and return all test modules from the specified start
directory, recursing into subdirectories to find them. Only test files
that match the pattern will be loaded. (Using shell style pattern
matching.)
All test modules must be importable from the top level of the project.
If the start directory is not the top leve... | def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
| set_implicit_top = False
if ((top_level_dir is None) and (self._top_level_dir is not None)):
top_level_dir = self._top_level_dir
elif (top_level_dir is None):
set_implicit_top = True
top_level_dir = start_dir
top_level_dir = os.path.abspath(top_level_dir)
if (top_level_dir no... |
'Used by discovery. Yields test suites it loads.'
| def _find_tests(self, start_dir, pattern):
| paths = os.listdir(start_dir)
for path in paths:
full_path = os.path.join(start_dir, path)
if os.path.isfile(full_path):
if (not VALID_MODULE_NAME.match(path)):
continue
if (not self._match_path(path, full_path, pattern)):
continue
... |
'Run the tests without collecting errors in a TestResult'
| def debug(self):
| for test in self:
test.debug()
|
'Run the tests without collecting errors in a TestResult'
| def debug(self):
| debug = _DebugResult()
self.run(debug, True)
|
'A file object is its own iterator, for example iter(f) returns f
(unless f is closed). When a file is used as an iterator, typically
in a for loop (for example, for line in f: print line), the next()
method is called repeatedly. This method returns the next input line,
or raises StopIteration when EOF is hit.'
| def next(self):
| _complain_ifclosed(self.closed)
r = self.readline()
if (not r):
raise StopIteration
return r
|
'Free the memory buffer.'
| def close(self):
| if (not self.closed):
self.closed = True
del self.buf
del self.pos
|
'Returns False because StringIO objects are not connected to a
tty-like device.'
| def isatty(self):
| _complain_ifclosed(self.closed)
return False
|
'Set the file\'s current position.
The mode argument is optional and defaults to 0 (absolute file
positioning); other values are 1 (seek relative to the current
position) and 2 (seek relative to the file\'s end).
There is no return value.'
| def seek(self, pos, mode=0):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
if (mode == 1):
pos += self.pos
elif (mode == 2):
pos += self.len
self.pos = max(0, pos)
|
'Return the file\'s current position.'
| def tell(self):
| _complain_ifclosed(self.closed)
return self.pos
|
'Read at most size bytes from the file
(less if the read hits EOF before obtaining size bytes).
If the size argument is negative or omitted, read all data until EOF
is reached. The bytes are returned as a string object. An empty
string is returned when EOF is encountered immediately.'
| def read(self, n=(-1)):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
if ((n is None) or (n < 0)):
newpos = self.len
else:
newpos = min((self.pos + n), self.len)
r = self.buf[self.pos:newpos]
self.pos = newpos
return r
|
'Read one entire line from the file.
A trailing newline character is kept in the string (but may be absent
when a file ends with an incomplete line). If the size argument is
present and non-negative, it is a maximum byte count (including the
trailing newline) and an incomplete line may be returned.
An empty string is r... | def readline(self, length=None):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
i = self.buf.find('\n', self.pos)
if (i < 0):
newpos = self.len
else:
newpos = (i + 1)
if ((length is not None) and (length > 0)):
if ((self.pos + length) ... |
'Read until EOF using readline() and return a list containing the
lines thus read.
If the optional sizehint argument is present, instead of reading up
to EOF, whole lines totalling approximately sizehint bytes (or more
to accommodate a final whole line).'
| def readlines(self, sizehint=0):
| total = 0
lines = []
line = self.readline()
while line:
lines.append(line)
total += len(line)
if (0 < sizehint <= total):
break
line = self.readline()
return lines
|
'Truncate the file\'s size.
If the optional size argument is present, the file is truncated to
(at most) that size. The size defaults to the current position.
The current file position is not changed unless the position
is beyond the new file size.
If the specified size exceeds the file\'s current size, the
file remain... | def truncate(self, size=None):
| _complain_ifclosed(self.closed)
if (size is None):
size = self.pos
elif (size < 0):
raise IOError(EINVAL, 'Negative size not allowed')
elif (size < self.pos):
self.pos = size
self.buf = self.getvalue()[:size]
self.len = size
return
|
'Write a string to the file.
There is no return value.'
| def write(self, s):
| _complain_ifclosed(self.closed)
if (not s):
return
if (not isinstance(s, basestring)):
s = str(s)
spos = self.pos
slen = self.len
if (spos == slen):
self.buflist.append(s)
self.len = self.pos = (spos + len(s))
return
if (spos > slen):
self.bufl... |
'Write a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings. There
is no return value.
(The name is intended to match readlines(); writelines() does not add
line separators.)'
| def writelines(self, iterable):
| write = self.write
for line in iterable:
write(line)
|
'Flush the internal buffer'
| def flush(self):
| _complain_ifclosed(self.closed)
|
'Retrieve the entire contents of the "file" at any time before
the StringIO object\'s close() method is called.
The StringIO object can accept either Unicode or 8-bit strings,
but mixing the two may take some care. If both are used, 8-bit
strings that cannot be interpreted as 7-bit ASCII (that use the
8th bit) will cau... | def getvalue(self):
| _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
return self.buf
|
'real_value, coded_value = value_decode(STRING)
Called prior to setting a cookie\'s value from the network
representation. The VALUE is the value read from HTTP
header.
Override this function to modify the behavior of cookies.'
| def value_decode(self, val):
| return (val, val)
|
'real_value, coded_value = value_encode(VALUE)
Called prior to setting a cookie\'s value from the dictionary
representation. The VALUE is the value being assigned.
Override this function to modify the behavior of cookies.'
| def value_encode(self, val):
| strval = str(val)
return (strval, strval)
|
'Private method for setting a cookie\'s value'
| def __set(self, key, real_value, coded_value):
| M = self.get(key, Morsel())
M.set(key, real_value, coded_value)
dict.__setitem__(self, key, M)
|
'Dictionary style assignment.'
| def __setitem__(self, key, value):
| (rval, cval) = self.value_encode(value)
self.__set(key, rval, cval)
|
'Return a string suitable for HTTP.'
| def output(self, attrs=None, header='Set-Cookie:', sep='\r\n'):
| result = []
items = self.items()
items.sort()
for (K, V) in items:
result.append(V.output(attrs, header))
return sep.join(result)
|
'Return a string suitable for JavaScript.'
| def js_output(self, attrs=None):
| result = []
items = self.items()
items.sort()
for (K, V) in items:
result.append(V.js_output(attrs))
return _nulljoin(result)
|
'Load cookies from a string (presumably HTTP_COOKIE) or
from a dictionary. Loading cookies from a dictionary \'d\'
is equivalent to calling:
map(Cookie.__setitem__, d.keys(), d.values())'
| def load(self, rawdata):
| if (type(rawdata) == type('')):
self.__ParseString(rawdata)
else:
for (k, v) in rawdata.items():
self[k] = v
|
'Return a distinct copy of the current font'
| def copy(self):
| return Font(self._root, **self.actual())
|
'Return actual font attributes'
| def actual(self, option=None):
| if option:
return self._call('font', 'actual', self.name, ('-' + option))
else:
return self._mkdict(self._split(self._call('font', 'actual', self.name)))
|
'Get font attribute'
| def cget(self, option):
| return self._call('font', 'config', self.name, ('-' + option))
|
'Modify font attributes'
| def config(self, **options):
| if options:
self._call('font', 'config', self.name, *self._set(options))
else:
return self._mkdict(self._split(self._call('font', 'config', self.name)))
|
'Return text width'
| def measure(self, text):
| return int(self._call('font', 'measure', self.name, text))
|
'Return font metrics.
For best performance, create a dummy widget
using this font before calling this method.'
| def metrics(self, *options):
| if options:
return int(self._call('font', 'metrics', self.name, self._get(options)))
else:
res = self._split(self._call('font', 'metrics', self.name))
options = {}
for i in range(0, len(res), 2):
options[res[i][1:]] = int(res[(i + 1)])
return options
|
'Construct a variable
MASTER can be given as master widget.
VALUE is an optional value (defaults to "")
NAME is an optional Tcl name (defaults to PY_VARnum).
If NAME matches an existing variable and VALUE is omitted
then the existing value is retained.'
| def __init__(self, master=None, value=None, name=None):
| global _varnum
if (not master):
master = _default_root
self._master = master
self._tk = master.tk
if name:
self._name = name
else:
self._name = ('PY_VAR' + repr(_varnum))
_varnum += 1
if (value is not None):
self.set(value)
elif (not self._tk.call(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.