desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'The final path component, if any.'
| @property
def name(self):
| parts = self._parts
if (len(parts) == (1 if (self._drv or self._root) else 0)):
return ''
return parts[(-1)]
|
'The final component\'s last suffix, if any.'
| @property
def suffix(self):
| name = self.name
i = name.rfind('.')
if (0 < i < (len(name) - 1)):
return name[i:]
else:
return ''
|
'A list of the final component\'s suffixes, if any.'
| @property
def suffixes(self):
| name = self.name
if name.endswith('.'):
return []
name = name.lstrip('.')
return [('.' + suffix) for suffix in name.split('.')[1:]]
|
'The final path component, minus its last suffix.'
| @property
def stem(self):
| name = self.name
i = name.rfind('.')
if (0 < i < (len(name) - 1)):
return name[:i]
else:
return name
|
'Return a new path with the file name changed.'
| def with_name(self, name):
| if (not self.name):
raise ValueError(('%r has an empty name' % (self,)))
(drv, root, parts) = self._flavour.parse_parts((name,))
if ((not name) or (name[(-1)] in [self._flavour.sep, self._flavour.altsep]) or drv or root or (len(parts) != 1)):
raise ValueError(('Invalid name ... |
'Return a new path with the file suffix changed (or added, if none).'
| def with_suffix(self, suffix):
| f = self._flavour
if ((f.sep in suffix) or (f.altsep and (f.altsep in suffix))):
raise ValueError(('Invalid suffix %r' % suffix))
if ((suffix and (not suffix.startswith('.'))) or (suffix == '.')):
raise ValueError(('Invalid suffix %r' % suffix))
name = self.name
if (not n... |
'Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.'
| def relative_to(self, *other):
| if (not other):
raise TypeError('need at least one argument')
parts = self._parts
drv = self._drv
root = self._root
if root:
abs_parts = ([drv, root] + parts[1:])
else:
abs_parts = parts
(to_drv, to_root, to_parts) = self._parse_args(other)
if to_root:... |
'An object providing sequence-like access to the
components in the filesystem path.'
| @property
def parts(self):
| try:
return self._pparts
except AttributeError:
self._pparts = tuple(self._parts)
return self._pparts
|
'Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored).'
| def joinpath(self, *args):
| return self._make_child(args)
|
'The logical parent of the path.'
| @property
def parent(self):
| drv = self._drv
root = self._root
parts = self._parts
if ((len(parts) == 1) and (drv or root)):
return self
return self._from_parsed_parts(drv, root, parts[:(-1)])
|
'A sequence of this path\'s logical parents.'
| @property
def parents(self):
| return _PathParents(self)
|
'True if the path is absolute (has both a root and, if applicable,
a drive).'
| def is_absolute(self):
| if (not self._root):
return False
return ((not self._flavour.has_drv) or bool(self._drv))
|
'Return True if the path contains one of the special names reserved
by the system, if any.'
| def is_reserved(self):
| return self._flavour.is_reserved(self._parts)
|
'Return True if this path matches the given pattern.'
| def match(self, path_pattern):
| cf = self._flavour.casefold
path_pattern = cf(path_pattern)
(drv, root, pat_parts) = self._flavour.parse_parts((path_pattern,))
if (not pat_parts):
raise ValueError('empty pattern')
if (drv and (drv != cf(self._drv))):
return False
if (root and (root != cf(self._root))):
... |
'Open the file pointed by this path and return a file descriptor,
as os.open() does.'
| def _raw_open(self, flags, mode=511):
| if self._closed:
self._raise_closed()
return self._accessor.open(self, flags, mode)
|
'Return a new path pointing to the current working directory
(as returned by os.getcwd()).'
| @classmethod
def cwd(cls):
| return cls(os.getcwd())
|
'Iterate over the files in this directory. Does not yield any
result for the special paths \'.\' and \'..\'.'
| def iterdir(self):
| if self._closed:
self._raise_closed()
for name in self._accessor.listdir(self):
if (name in {'.', '..'}):
continue
(yield self._make_child_relpath(name))
if self._closed:
self._raise_closed()
|
'Iterate over this subtree and yield all existing files (of any
kind, including directories) matching the given pattern.'
| def glob(self, pattern):
| pattern = self._flavour.casefold(pattern)
(drv, root, pattern_parts) = self._flavour.parse_parts((pattern,))
if (drv or root):
raise NotImplementedError('Non-relative patterns are unsupported')
selector = _make_selector(tuple(pattern_parts))
for p in selector.select_from(self):
... |
'Recursively yield all existing files (of any kind, including
directories) matching the given pattern, anywhere in this subtree.'
| def rglob(self, pattern):
| pattern = self._flavour.casefold(pattern)
(drv, root, pattern_parts) = self._flavour.parse_parts((pattern,))
if (drv or root):
raise NotImplementedError('Non-relative patterns are unsupported')
selector = _make_selector((('**',) + tuple(pattern_parts)))
for p in selector.select_from... |
'Return an absolute version of this path. This function works
even if the path doesn\'t point to anything.
No normalization is done, i.e. all \'.\' and \'..\' will be kept along.
Use resolve() to get the canonical path to a file.'
| def absolute(self):
| if self._closed:
self._raise_closed()
if self.is_absolute():
return self
obj = self._from_parts(([os.getcwd()] + self._parts), init=False)
obj._init(template=self)
return obj
|
'Make the path absolute, resolving all symlinks on the way and also
normalizing it (for example turning slashes into backslashes under
Windows).'
| def resolve(self):
| if self._closed:
self._raise_closed()
s = self._flavour.resolve(self)
if (s is None):
self.stat()
s = str(self.absolute())
normed = self._flavour.pathmod.normpath(s)
obj = self._from_parts((normed,), init=False)
obj._init(template=self)
return obj
|
'Return the result of the stat() system call on this path, like
os.stat() does.'
| def stat(self):
| return self._accessor.stat(self)
|
'Return the login name of the file owner.'
| def owner(self):
| import pwd
return pwd.getpwuid(self.stat().st_uid).pw_name
|
'Return the group name of the file gid.'
| def group(self):
| import grp
return grp.getgrgid(self.stat().st_gid).gr_name
|
'Open the file pointed by this path and return a file object, as
the built-in open() function does.'
| def open(self, mode='r', buffering=(-1), encoding=None, errors=None, newline=None):
| if self._closed:
self._raise_closed()
return io.open(str(self), mode, buffering, encoding, errors, newline, opener=self._opener)
|
'Create this file with the given access mode, if it doesn\'t exist.'
| def touch(self, mode=438, exist_ok=True):
| if self._closed:
self._raise_closed()
if exist_ok:
try:
self._accessor.utime(self, None)
except OSError:
pass
else:
return
flags = (os.O_CREAT | os.O_WRONLY)
if (not exist_ok):
flags |= os.O_EXCL
fd = self._raw_open(flags, m... |
'Change the permissions of the path, like os.chmod().'
| def chmod(self, mode):
| if self._closed:
self._raise_closed()
self._accessor.chmod(self, mode)
|
'Like chmod(), except if the path points to a symlink, the symlink\'s
permissions are changed, rather than its target\'s.'
| def lchmod(self, mode):
| if self._closed:
self._raise_closed()
self._accessor.lchmod(self, mode)
|
'Remove this file or link.
If the path is a directory, use rmdir() instead.'
| def unlink(self):
| if self._closed:
self._raise_closed()
self._accessor.unlink(self)
|
'Remove this directory. The directory must be empty.'
| def rmdir(self):
| if self._closed:
self._raise_closed()
self._accessor.rmdir(self)
|
'Like stat(), except if the path points to a symlink, the symlink\'s
status information is returned, rather than its target\'s.'
| def lstat(self):
| if self._closed:
self._raise_closed()
return self._accessor.lstat(self)
|
'Rename this path to the given path.'
| def rename(self, target):
| if self._closed:
self._raise_closed()
self._accessor.rename(self, target)
|
'Rename this path to the given path, clobbering the existing
destination if it exists.'
| def replace(self, target):
| if self._closed:
self._raise_closed()
self._accessor.replace(self, target)
|
'Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of os.symlink\'s.'
| def symlink_to(self, target, target_is_directory=False):
| if self._closed:
self._raise_closed()
self._accessor.symlink(target, self, target_is_directory)
|
'Whether this path exists.'
| def exists(self):
| try:
self.stat()
except OSError as e:
if (e.errno != ENOENT):
raise
return False
return True
|
'Whether this path is a directory.'
| def is_dir(self):
| try:
return S_ISDIR(self.stat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Whether this path is a regular file (also True for symlinks pointing
to regular files).'
| def is_file(self):
| try:
return S_ISREG(self.stat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Whether this path is a symbolic link.'
| def is_symlink(self):
| try:
return S_ISLNK(self.lstat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Whether this path is a block device.'
| def is_block_device(self):
| try:
return S_ISBLK(self.stat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Whether this path is a character device.'
| def is_char_device(self):
| try:
return S_ISCHR(self.stat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Whether this path is a FIFO.'
| def is_fifo(self):
| try:
return S_ISFIFO(self.stat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Whether this path is a socket.'
| def is_socket(self):
| try:
return S_ISSOCK(self.stat().st_mode)
except OSError as e:
if (e.errno != ENOENT):
raise
return False
|
'Create a new HMAC object.
key: key for the keyed hash object.
msg: Initial input for the hash, if provided.
digestmod: A module supporting PEP 247. *OR*
A hashlib constructor returning a new hash object. *OR*
A hash name suitable for hashlib.new().
Defaults to hashlib.md5.
Implicit default to hashlib.md5 ... | def __init__(self, key, msg=None, digestmod=None):
| if (not isinstance(key, (bytes, bytearray))):
raise TypeError(('key: expected bytes or bytearray, but got %r' % type(key).__name__))
if (digestmod is None):
_warnings.warn('HMAC() without an explicit digestmod argument is deprecated.', PendingDeprecation... |
'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__.__new__(self.__class__)
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()
|
'Called when the given test is about to be run'
| def startTest(self, test):
| self.testsRun += 1
self._mirrorOutput = False
self._setupStdout()
|
'Called when the given test has been run'
| def stopTest(self, test):
| self._restoreStdout()
self._mirrorOutput = False
|
'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 at the end of a subtest.
\'err\' is None if the subtest ended successfully, otherwise it\'s a
tuple of values as returned by sys.exc_info().'
| @failfast
def addSubTest(self, test, subtest, err):
| if (err is not None):
if issubclass(err[0], test.failureException):
errors = self.failures
else:
errors = self.errors
errors.append((subtest, 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) and ((not hasattr(self, 'unexpectedSuccesses')) or (len(self.unexpectedSuccesses) == 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
with warnings.catch_warnings():
if self.warnings:
warnings.simplefilter(self.warnings)
if (self.warnings in ['default', 'always']):
warnings.... |
'Tests shortDescription() for a method with a docstring.'
| @unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def testShortDescriptionWithOneLineDocstring(self):
| self.assertEqual(self.shortDescription(), 'Tests shortDescription() for a method with a docstring.')
|
'Tests shortDescription() for a method with a longer docstring.
This method ensures that only the first line of a docstring is
returned used in the short description, no matter how long the
whole thing is.'
| @unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above')
def testShortDescriptionWithMultiLineDocstring(self):
| self.assertEqual(self.shortDescription(), 'Tests shortDescription() for a method with a longer docstring.')
|
'Test that the deprecated methods raise a DeprecationWarning. See #9424.'
| def testDeprecatedMethodNames(self):
| old = ((self.failIfEqual, (3, 5)), (self.assertNotEquals, (3, 5)), (self.failUnlessEqual, (3, 3)), (self.assertEquals, (3, 3)), (self.failUnlessAlmostEqual, (2.0, 2.0)), (self.assertAlmostEquals, (2.0, 2.0)), (self.failIfAlmostEqual, (3.0, 5.0)), (self.assertNotAlmostEquals, (3.0, 5.0)), (self.failUnless, (True,)),... |
'Test that the deprecated fail* methods get removed in 3.x'
| def _testDeprecatedFailMethods(self):
| if (sys.version_info[:2] < (3, 3)):
return
deprecated_names = ['failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual', 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf', 'assertDictContainsSubset']
for deprecated_name in deprecated_names:
with self.assertRaises(AttributeErro... |
'Check that warnings argument of TextTestRunner correctly affects the
behavior of the warnings.'
| def test_warnings(self):
| def get_parse_out_err(p):
return [b.splitlines() for b in p.communicate()]
opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(__file__))
ae_msg = 'Please use assertEqual instead.'
at_msg = 'Please use assertTrue instead.'
p = subprocess.Popen([s... |
'Test the warnings argument'
| def testWarning(self):
| class FakeTP(unittest.TestProgram, ):
def parseArgs(self, *args, **kw):
pass
def runTests(self, *args, **kw):
pass
warnoptions = sys.warnoptions[:]
try:
sys.warnoptions[:] = []
self.assertEqual(FakeTP().warnings, 'default')
self.assertEqual(Fak... |
'Stop holding a reference to the TestCase at index.'
| def _removeTestAtIndex(self, index):
| try:
test = self._tests[index]
except TypeError:
pass
else:
if hasattr(test, 'countTestCases'):
self._removed_tests += test.countTestCases()
self._tests[index] = None
|
'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)
|
'Read at least wtd bytes (or until EOF)'
| def read(self, totalwtd):
| decdata = ''
wtd = totalwtd
while (wtd > 0):
if self.eof:
return decdata
wtd = (((wtd + 2) // 3) * 4)
data = self.ifp.read(wtd)
while True:
try:
(decdatacur, self.eof) = binascii.a2b_hqx(data)
break
except bi... |
'The implementation for this class returns the max_count attribute from
the specialized header class that would be used to construct a header
of type \'name\'.'
| def header_max_count(self, name):
| return self.header_factory[name].max_count
|
'The name is parsed as everything up to the \':\' and returned unmodified.
The value is determined by stripping leading whitespace off the
remainder of the first line, joining all subsequent lines together, and
stripping any trailing carriage return or linefeed characters. (This
is the same as Compat32).'
| def header_source_parse(self, sourcelines):
| (name, value) = sourcelines[0].split(':', 1)
value = (value.lstrip(' DCTB ') + ''.join(sourcelines[1:]))
return (name, value.rstrip('\r\n'))
|
'The name is returned unchanged. If the input value has a \'name\'
attribute and it matches the name ignoring case, the value is returned
unchanged. Otherwise the name and value are passed to header_factory
method, and the resulting custom header object is returned as the
value. In this case a ValueError is raised i... | def header_store_parse(self, name, value):
| if (hasattr(value, 'name') and (value.name.lower() == name.lower())):
return (name, value)
if (isinstance(value, str) and (len(value.splitlines()) > 1)):
raise ValueError('Header values may not contain linefeed or carriage return characters')
return (name, self.hea... |
'If the value has a \'name\' attribute, it is returned to unmodified.
Otherwise the name and the value with any linesep characters removed
are passed to the header_factory method, and the resulting custom
header object is returned. Any surrogateescaped bytes get turned
into the unicode unknown-character glyph.'
| def header_fetch_parse(self, name, value):
| if hasattr(value, 'name'):
return value
return self.header_factory(name, ''.join(value.splitlines()))
|
'Header folding is controlled by the refold_source policy setting. A
value is considered to be a \'source value\' if and only if it does not
have a \'name\' attribute (having a \'name\' attribute means it is a header
object of some sort). If a source value needs to be refolded according
to the policy, it is converted... | def fold(self, name, value):
| return self._fold(name, value, refold_binary=True)
|
'The same as fold if cte_type is 7bit, except that the returned value is
bytes.
If cte_type is 8bit, non-ASCII binary data is converted back into
bytes. Headers with binary data are not refolded, regardless of the
refold_header setting, since there is no way to know whether the binary
data consists of single byte char... | def fold_binary(self, name, value):
| folded = self._fold(name, value, refold_binary=(self.cte_type == '7bit'))
return folded.encode('ascii', 'surrogateescape')
|
'Initialize a new instance.
`field\' is an unparsed address header field, containing
one or more addresses.'
| def __init__(self, field):
| self.specials = '()<>@,:;."[]'
self.pos = 0
self.LWS = ' DCTB '
self.CR = '\r\n'
self.FWS = (self.LWS + self.CR)
self.atomends = ((self.specials + self.LWS) + self.CR)
self.phraseends = self.atomends.replace('.', '')
self.field = field
self.commentlist = []
|
'Skip white space and extract comments.'
| def gotonext(self):
| wslist = []
while (self.pos < len(self.field)):
if (self.field[self.pos] in (self.LWS + '\n\r')):
if (self.field[self.pos] not in '\n\r'):
wslist.append(self.field[self.pos])
self.pos += 1
elif (self.field[self.pos] == '('):
self.commentlist.ap... |
'Parse all addresses.
Returns a list containing all of the addresses.'
| def getaddrlist(self):
| result = []
while (self.pos < len(self.field)):
ad = self.getaddress()
if ad:
result += ad
else:
result.append(('', ''))
return result
|
'Parse the next address.'
| def getaddress(self):
| self.commentlist = []
self.gotonext()
oldpos = self.pos
oldcl = self.commentlist
plist = self.getphraselist()
self.gotonext()
returnlist = []
if (self.pos >= len(self.field)):
if plist:
returnlist = [(SPACE.join(self.commentlist), plist[0])]
elif (self.field[self.... |
'Parse a route address (Return-path value).
This method just skips all the route stuff and returns the addrspec.'
| def getrouteaddr(self):
| if (self.field[self.pos] != '<'):
return
expectroute = False
self.pos += 1
self.gotonext()
adlist = ''
while (self.pos < len(self.field)):
if expectroute:
self.getdomain()
expectroute = False
elif (self.field[self.pos] == '>'):
self.pos... |
'Parse an RFC 2822 addr-spec.'
| def getaddrspec(self):
| aslist = []
self.gotonext()
while (self.pos < len(self.field)):
preserve_ws = True
if (self.field[self.pos] == '.'):
if (aslist and (not aslist[(-1)].strip())):
aslist.pop()
aslist.append('.')
self.pos += 1
preserve_ws = False
... |
'Get the complete domain name from an address.'
| def getdomain(self):
| sdlist = []
while (self.pos < len(self.field)):
if (self.field[self.pos] in self.LWS):
self.pos += 1
elif (self.field[self.pos] == '('):
self.commentlist.append(self.getcomment())
elif (self.field[self.pos] == '['):
sdlist.append(self.getdomainliteral(... |
'Parse a header fragment delimited by special characters.
`beginchar\' is the start character for the fragment.
If self is not looking at an instance of `beginchar\' then
getdelimited returns the empty string.
`endchars\' is a sequence of allowable end-delimiting characters.
Parsing stops when one of these is encounter... | def getdelimited(self, beginchar, endchars, allowcomments=True):
| if (self.field[self.pos] != beginchar):
return ''
slist = ['']
quote = False
self.pos += 1
while (self.pos < len(self.field)):
if quote:
slist.append(self.field[self.pos])
quote = False
elif (self.field[self.pos] in endchars):
self.pos += 1... |
'Get a quote-delimited fragment from self\'s field.'
| def getquote(self):
| return self.getdelimited('"', '"\r', False)
|
'Get a parenthesis-delimited fragment from self\'s field.'
| def getcomment(self):
| return self.getdelimited('(', ')\r', True)
|
'Parse an RFC 2822 domain-literal.'
| def getdomainliteral(self):
| return ('[%s]' % self.getdelimited('[', ']\r', False))
|
'Parse an RFC 2822 atom.
Optional atomends specifies a different set of end token delimiters
(the default is to use self.atomends). This is used e.g. in
getphraselist() since phrase endings must not include the `.\' (which
is legal in phrases).'
| def getatom(self, atomends=None):
| atomlist = ['']
if (atomends is None):
atomends = self.atomends
while (self.pos < len(self.field)):
if (self.field[self.pos] in atomends):
break
else:
atomlist.append(self.field[self.pos])
self.pos += 1
return EMPTYSTRING.join(atomlist)
|
'Parse a sequence of RFC 2822 phrases.
A phrase is a sequence of words, which are in turn either RFC 2822
atoms or quoted-strings. Phrases are canonicalized by squeezing all
runs of continuous whitespace into one space.'
| def getphraselist(self):
| plist = []
while (self.pos < len(self.field)):
if (self.field[self.pos] in self.FWS):
self.pos += 1
elif (self.field[self.pos] == '"'):
plist.append(self.getquote())
elif (self.field[self.pos] == '('):
self.commentlist.append(self.getcomment())
... |
'Return the content-transfer-encoding used for body encoding.
This is either the string `quoted-printable\' or `base64\' depending on
the encoding used, or it is a function in which case you should call
the function with a single argument, the Message object being
encoded. The function should then set the Content-Tran... | def get_body_encoding(self):
| assert (self.body_encoding != SHORTEST)
if (self.body_encoding == QP):
return 'quoted-printable'
elif (self.body_encoding == BASE64):
return 'base64'
else:
return encode_7or8bit
|
'Return the output character set.
This is self.output_charset if that is not None, otherwise it is
self.input_charset.'
| def get_output_charset(self):
| return (self.output_charset or self.input_charset)
|
'Header-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
this charset\'s `header_encoding`.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set\'s
output codec.
:return: The encoded... | def header_encode(self, string):
| codec = (self.output_codec or 'us-ascii')
header_bytes = _encode(string, codec)
encoder_module = self._get_encoder(header_bytes)
if (encoder_module is None):
return string
return encoder_module.header_encode(header_bytes, codec)
|
'Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set\'s
output codec.
:pa... | def header_encode_lines(self, string, maxlengths):
| codec = (self.output_codec or 'us-ascii')
header_bytes = _encode(string, codec)
encoder_module = self._get_encoder(header_bytes)
encoder = partial(encoder_module.header_encode, charset=codec)
charset = self.get_output_charset()
extra = (len(charset) + RFC2047_CHROME_LEN)
lines = []
curre... |
'Body-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
self.body_encoding. If body_encoding is None, we assume the
output charset is a 7bit encoding, so re-encoding the decoded
string using the ascii codec produces the correct string version
of the con... | def body_encode(self, string):
| if (not string):
return string
if (self.body_encoding is BASE64):
if isinstance(string, str):
string = string.encode(self.output_charset)
return email.base64mime.body_encode(string)
elif (self.body_encoding is QP):
if isinstance(string, str):
string = ... |
'Create a MIME-compliant header that can contain many character sets.
Optional s is the initial header value. If None, the initial header
value is not set. You can later append to the header with .append()
method calls. s may be a byte string or a Unicode string, but see the
.append() documentation for semantics.
Op... | def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict'):
| if (charset is None):
charset = USASCII
elif (not isinstance(charset, Charset)):
charset = Charset(charset)
self._charset = charset
self._continuation_ws = continuation_ws
self._chunks = []
if (s is not None):
self.append(s, charset, errors)
if (maxlinelen is None):
... |
'Return the string value of the header.'
| def __str__(self):
| self._normalize()
uchunks = []
lastcs = None
lastspace = None
for (string, charset) in self._chunks:
nextcs = charset
if (nextcs == _charset.UNKNOWN8BIT):
original_bytes = string.encode('ascii', 'surrogateescape')
string = original_bytes.decode('ascii', 'repla... |
'Append a string to the MIME header.
Optional charset, if given, should be a Charset instance or the name
of a character set (which will be converted to a Charset instance). A
value of None (the default) means that the charset given in the
constructor is used.
s may be a byte string or a Unicode string. If it is a by... | def append(self, s, charset=None, errors='strict'):
| if (charset is None):
charset = self._charset
elif (not isinstance(charset, Charset)):
charset = Charset(charset)
if (not isinstance(s, str)):
input_charset = (charset.input_codec or 'us-ascii')
if (input_charset == _charset.UNKNOWN8BIT):
s = s.decode('us-ascii', ... |
'True if string s is not a ctext character of RFC822.'
| def _nonctext(self, s):
| return (s.isspace() or (s in ('(', ')', '\\')))
|
'Encode a message header into an RFC-compliant format.
There are many issues involved in converting a given string for use in
an email header. Only certain character sets are readable in most
email clients, and as header strings can only contain a subset of
7-bit ASCII, care must be taken to properly convert and encod... | def encode(self, splitchars=';, DCTB ', maxlinelen=None, linesep='\n'):
| self._normalize()
if (maxlinelen is None):
maxlinelen = self._maxlinelen
if (maxlinelen == 0):
maxlinelen = 1000000
formatter = _ValueFormatter(self._headerlen, maxlinelen, self._continuation_ws, splitchars)
lastcs = None
hasspace = lastspace = None
for (string, charset) in s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.