index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
20,647 | email.message | get | Get a header value.
Like __getitem__() but return failobj instead of None when the field
is missing.
| def get(self, name, failobj=None):
"""Get a header value.
Like __getitem__() but return failobj instead of None when the field
is missing.
"""
name = name.lower()
for k, v in self._headers:
if k.lower() == name:
return self.policy.header_fetch_parse(k, v)
return failobj
| (self, name, failobj=None) |
20,648 | email.message | get_all | Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original
message, and may contain duplicates. Any fields deleted and
re-inserted are always appended to the header list.
If no such fields exist, failobj is returned (defaults to None).
| def get_all(self, name, failobj=None):
"""Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original
message, and may contain duplicates. Any fields deleted and
re-inserted are always appended to the header list.
If no such fields exist, failobj is returned (defaults to None).
"""
values = []
name = name.lower()
for k, v in self._headers:
if k.lower() == name:
values.append(self.policy.header_fetch_parse(k, v))
if not values:
return failobj
return values
| (self, name, failobj=None) |
20,649 | email.message | get_boundary | Return the boundary associated with the payload if present.
The boundary is extracted from the Content-Type header's `boundary'
parameter, and it is unquoted.
| def get_boundary(self, failobj=None):
"""Return the boundary associated with the payload if present.
The boundary is extracted from the Content-Type header's `boundary'
parameter, and it is unquoted.
"""
missing = object()
boundary = self.get_param('boundary', missing)
if boundary is missing:
return failobj
# RFC 2046 says that boundaries may begin but not end in w/s
return utils.collapse_rfc2231_value(boundary).rstrip()
| (self, failobj=None) |
20,650 | email.message | get_charset | Return the Charset instance associated with the message's payload.
| def get_charset(self):
"""Return the Charset instance associated with the message's payload.
"""
return self._charset
| (self) |
20,651 | email.message | get_charsets | Return a list containing the charset(s) used in this message.
The returned list of items describes the Content-Type headers'
charset parameter for this message and all the subparts in its
payload.
Each item will either be a string (the value of the charset parameter
in the Content-Type header of that part) or the value of the
'failobj' parameter (defaults to None), if the part does not have a
main MIME type of "text", or the charset is not defined.
The list will contain one string for each part of the message, plus
one for the container message (i.e. self), so that a non-multipart
message will still return a list of length 1.
| def get_charsets(self, failobj=None):
"""Return a list containing the charset(s) used in this message.
The returned list of items describes the Content-Type headers'
charset parameter for this message and all the subparts in its
payload.
Each item will either be a string (the value of the charset parameter
in the Content-Type header of that part) or the value of the
'failobj' parameter (defaults to None), if the part does not have a
main MIME type of "text", or the charset is not defined.
The list will contain one string for each part of the message, plus
one for the container message (i.e. self), so that a non-multipart
message will still return a list of length 1.
"""
return [part.get_content_charset(failobj) for part in self.walk()]
| (self, failobj=None) |
20,652 | email.message | get_content_charset | Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.
| def get_content_charset(self, failobj=None):
"""Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.
"""
missing = object()
charset = self.get_param('charset', missing)
if charset is missing:
return failobj
if isinstance(charset, tuple):
# RFC 2231 encoded, so decode it, and it better end up as ascii.
pcharset = charset[0] or 'us-ascii'
try:
# LookupError will be raised if the charset isn't known to
# Python. UnicodeError will be raised if the encoded text
# contains a character not in the charset.
as_bytes = charset[2].encode('raw-unicode-escape')
charset = str(as_bytes, pcharset)
except (LookupError, UnicodeError):
charset = charset[2]
# charset characters must be in us-ascii range
try:
charset.encode('us-ascii')
except UnicodeError:
return failobj
# RFC 2046, $4.1.2 says charsets are not case sensitive
return charset.lower()
| (self, failobj=None) |
20,653 | email.message | get_content_disposition | Return the message's content-disposition if it exists, or None.
The return values can be either 'inline', 'attachment' or None
according to the rfc2183.
| def get_content_disposition(self):
"""Return the message's content-disposition if it exists, or None.
The return values can be either 'inline', 'attachment' or None
according to the rfc2183.
"""
value = self.get('content-disposition')
if value is None:
return None
c_d = _splitparam(value)[0].lower()
return c_d
| (self) |
20,654 | email.message | get_content_maintype | Return the message's main content type.
This is the `maintype' part of the string returned by
get_content_type().
| def get_content_maintype(self):
"""Return the message's main content type.
This is the `maintype' part of the string returned by
get_content_type().
"""
ctype = self.get_content_type()
return ctype.split('/')[0]
| (self) |
20,655 | email.message | get_content_subtype | Returns the message's sub-content type.
This is the `subtype' part of the string returned by
get_content_type().
| def get_content_subtype(self):
"""Returns the message's sub-content type.
This is the `subtype' part of the string returned by
get_content_type().
"""
ctype = self.get_content_type()
return ctype.split('/')[1]
| (self) |
20,656 | email.message | get_content_type | Return the message's content type.
The returned string is coerced to lower case of the form
`maintype/subtype'. If there was no Content-Type header in the
message, the default type as given by get_default_type() will be
returned. Since according to RFC 2045, messages always have a default
type this will always return a value.
RFC 2045 defines a message's default type to be text/plain unless it
appears inside a multipart/digest container, in which case it would be
message/rfc822.
| def get_content_type(self):
"""Return the message's content type.
The returned string is coerced to lower case of the form
`maintype/subtype'. If there was no Content-Type header in the
message, the default type as given by get_default_type() will be
returned. Since according to RFC 2045, messages always have a default
type this will always return a value.
RFC 2045 defines a message's default type to be text/plain unless it
appears inside a multipart/digest container, in which case it would be
message/rfc822.
"""
missing = object()
value = self.get('content-type', missing)
if value is missing:
# This should have no parameters
return self.get_default_type()
ctype = _splitparam(value)[0].lower()
# RFC 2045, section 5.2 says if its invalid, use text/plain
if ctype.count('/') != 1:
return 'text/plain'
return ctype
| (self) |
20,657 | email.message | get_default_type | Return the `default' content type.
Most messages have a default content type of text/plain, except for
messages that are subparts of multipart/digest containers. Such
subparts have a default content type of message/rfc822.
| def get_default_type(self):
"""Return the `default' content type.
Most messages have a default content type of text/plain, except for
messages that are subparts of multipart/digest containers. Such
subparts have a default content type of message/rfc822.
"""
return self._default_type
| (self) |
20,658 | email.message | get_filename | Return the filename associated with the payload if present.
The filename is extracted from the Content-Disposition header's
`filename' parameter, and it is unquoted. If that header is missing
the `filename' parameter, this method falls back to looking for the
`name' parameter.
| def get_filename(self, failobj=None):
"""Return the filename associated with the payload if present.
The filename is extracted from the Content-Disposition header's
`filename' parameter, and it is unquoted. If that header is missing
the `filename' parameter, this method falls back to looking for the
`name' parameter.
"""
missing = object()
filename = self.get_param('filename', missing, 'content-disposition')
if filename is missing:
filename = self.get_param('name', missing, 'content-type')
if filename is missing:
return failobj
return utils.collapse_rfc2231_value(filename).strip()
| (self, failobj=None) |
20,659 | email.message | get_param | Return the parameter value if found in the Content-Type header.
Optional failobj is the object to return if there is no Content-Type
header, or the Content-Type header has no such parameter. Optional
header is the header to search instead of Content-Type.
Parameter keys are always compared case insensitively. The return
value can either be a string, or a 3-tuple if the parameter was RFC
2231 encoded. When it's a 3-tuple, the elements of the value are of
the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
LANGUAGE can be None, in which case you should consider VALUE to be
encoded in the us-ascii charset. You can usually ignore LANGUAGE.
The parameter value (either the returned string, or the VALUE item in
the 3-tuple) is always unquoted, unless unquote is set to False.
If your application doesn't care whether the parameter was RFC 2231
encoded, it can turn the return value into a string as follows:
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)
| def get_param(self, param, failobj=None, header='content-type',
unquote=True):
"""Return the parameter value if found in the Content-Type header.
Optional failobj is the object to return if there is no Content-Type
header, or the Content-Type header has no such parameter. Optional
header is the header to search instead of Content-Type.
Parameter keys are always compared case insensitively. The return
value can either be a string, or a 3-tuple if the parameter was RFC
2231 encoded. When it's a 3-tuple, the elements of the value are of
the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
LANGUAGE can be None, in which case you should consider VALUE to be
encoded in the us-ascii charset. You can usually ignore LANGUAGE.
The parameter value (either the returned string, or the VALUE item in
the 3-tuple) is always unquoted, unless unquote is set to False.
If your application doesn't care whether the parameter was RFC 2231
encoded, it can turn the return value into a string as follows:
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)
"""
if header not in self:
return failobj
for k, v in self._get_params_preserve(failobj, header):
if k.lower() == param.lower():
if unquote:
return _unquotevalue(v)
else:
return v
return failobj
| (self, param, failobj=None, header='content-type', unquote=True) |
20,660 | email.message | get_params | Return the message's Content-Type parameters, as a list.
The elements of the returned list are 2-tuples of key/value pairs, as
split on the `=' sign. The left hand side of the `=' is the key,
while the right hand side is the value. If there is no `=' sign in
the parameter the value is the empty string. The value is as
described in the get_param() method.
Optional failobj is the object to return if there is no Content-Type
header. Optional header is the header to search instead of
Content-Type. If unquote is True, the value is unquoted.
| def get_params(self, failobj=None, header='content-type', unquote=True):
"""Return the message's Content-Type parameters, as a list.
The elements of the returned list are 2-tuples of key/value pairs, as
split on the `=' sign. The left hand side of the `=' is the key,
while the right hand side is the value. If there is no `=' sign in
the parameter the value is the empty string. The value is as
described in the get_param() method.
Optional failobj is the object to return if there is no Content-Type
header. Optional header is the header to search instead of
Content-Type. If unquote is True, the value is unquoted.
"""
missing = object()
params = self._get_params_preserve(missing, header)
if params is missing:
return failobj
if unquote:
return [(k, _unquotevalue(v)) for k, v in params]
else:
return params
| (self, failobj=None, header='content-type', unquote=True) |
20,661 | email.message | get_payload | Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned.
| def get_payload(self, i=None, decode=False):
"""Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned.
"""
# Here is the logic table for this code, based on the email5.0.0 code:
# i decode is_multipart result
# ------ ------ ------------ ------------------------------
# None True True None
# i True True None
# None False True _payload (a list)
# i False True _payload element i (a Message)
# i False False error (not a list)
# i True False error (not a list)
# None False False _payload
# None True False _payload decoded (bytes)
# Note that Barry planned to factor out the 'decode' case, but that
# isn't so easy now that we handle the 8 bit data, which needs to be
# converted in both the decode and non-decode path.
if self.is_multipart():
if decode:
return None
if i is None:
return self._payload
else:
return self._payload[i]
# For backward compatibility, Use isinstance and this error message
# instead of the more logical is_multipart test.
if i is not None and not isinstance(self._payload, list):
raise TypeError('Expected list, got %s' % type(self._payload))
payload = self._payload
# cte might be a Header, so for now stringify it.
cte = str(self.get('content-transfer-encoding', '')).lower()
# payload may be bytes here.
if isinstance(payload, str):
if utils._has_surrogates(payload):
bpayload = payload.encode('ascii', 'surrogateescape')
if not decode:
try:
payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace')
except LookupError:
payload = bpayload.decode('ascii', 'replace')
elif decode:
try:
bpayload = payload.encode('ascii')
except UnicodeError:
# This won't happen for RFC compliant messages (messages
# containing only ASCII code points in the unicode input).
# If it does happen, turn the string into bytes in a way
# guaranteed not to fail.
bpayload = payload.encode('raw-unicode-escape')
if not decode:
return payload
if cte == 'quoted-printable':
return quopri.decodestring(bpayload)
elif cte == 'base64':
# XXX: this is a bit of a hack; decode_b should probably be factored
# out somewhere, but I haven't figured out where yet.
value, defects = decode_b(b''.join(bpayload.splitlines()))
for defect in defects:
self.policy.handle_defect(self, defect)
return value
elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
in_file = BytesIO(bpayload)
out_file = BytesIO()
try:
uu.decode(in_file, out_file, quiet=True)
return out_file.getvalue()
except uu.Error:
# Some decoding problem
return bpayload
if isinstance(payload, str):
return bpayload
return payload
| (self, i=None, decode=False) |
20,662 | email.message | get_unixfrom | null | def get_unixfrom(self):
return self._unixfrom
| (self) |
20,663 | http.client | getallmatchingheaders | Find all header lines matching a given header name.
Look through the list of headers and find all lines matching a given
header name (and their continuation lines). A list of the lines is
returned, without interpretation. If the header does not occur, an
empty list is returned. If the header occurs multiple times, all
occurrences are returned. Case is not important in the header name.
| def getallmatchingheaders(self, name):
"""Find all header lines matching a given header name.
Look through the list of headers and find all lines matching a given
header name (and their continuation lines). A list of the lines is
returned, without interpretation. If the header does not occur, an
empty list is returned. If the header occurs multiple times, all
occurrences are returned. Case is not important in the header name.
"""
name = name.lower() + ':'
n = len(name)
lst = []
hit = 0
for line in self.keys():
if line[:n].lower() == name:
hit = 1
elif not line[:1].isspace():
hit = 0
if hit:
lst.append(line)
return lst
| (self, name) |
20,664 | email.message | is_multipart | Return True if the message consists of multiple parts. | def is_multipart(self):
"""Return True if the message consists of multiple parts."""
return isinstance(self._payload, list)
| (self) |
20,665 | email.message | items | Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
| def items(self):
"""Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers]
| (self) |
20,666 | email.message | keys | Return a list of all the message's header field names.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
| def keys(self):
"""Return a list of all the message's header field names.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [k for k, v in self._headers]
| (self) |
20,667 | email.message | raw_items | Return the (name, value) header pairs without modification.
This is an "internal" API, intended only for use by a generator.
| def raw_items(self):
"""Return the (name, value) header pairs without modification.
This is an "internal" API, intended only for use by a generator.
"""
return iter(self._headers.copy())
| (self) |
20,668 | email.message | replace_header | Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised.
| def replace_header(self, _name, _value):
"""Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised.
"""
_name = _name.lower()
for i, (k, v) in zip(range(len(self._headers)), self._headers):
if k.lower() == _name:
self._headers[i] = self.policy.header_store_parse(k, _value)
break
else:
raise KeyError(_name)
| (self, _name, _value) |
20,669 | email.message | set_boundary | Set the boundary parameter in Content-Type to 'boundary'.
This is subtly different than deleting the Content-Type header and
adding a new one with a new boundary parameter via add_header(). The
main difference is that using the set_boundary() method preserves the
order of the Content-Type header in the original message.
HeaderParseError is raised if the message has no Content-Type header.
| def set_boundary(self, boundary):
"""Set the boundary parameter in Content-Type to 'boundary'.
This is subtly different than deleting the Content-Type header and
adding a new one with a new boundary parameter via add_header(). The
main difference is that using the set_boundary() method preserves the
order of the Content-Type header in the original message.
HeaderParseError is raised if the message has no Content-Type header.
"""
missing = object()
params = self._get_params_preserve(missing, 'content-type')
if params is missing:
# There was no Content-Type header, and we don't know what type
# to set it to, so raise an exception.
raise errors.HeaderParseError('No Content-Type header found')
newparams = []
foundp = False
for pk, pv in params:
if pk.lower() == 'boundary':
newparams.append(('boundary', '"%s"' % boundary))
foundp = True
else:
newparams.append((pk, pv))
if not foundp:
# The original Content-Type header had no boundary attribute.
# Tack one on the end. BAW: should we raise an exception
# instead???
newparams.append(('boundary', '"%s"' % boundary))
# Replace the existing Content-Type header with the new value
newheaders = []
for h, v in self._headers:
if h.lower() == 'content-type':
parts = []
for k, v in newparams:
if v == '':
parts.append(k)
else:
parts.append('%s=%s' % (k, v))
val = SEMISPACE.join(parts)
newheaders.append(self.policy.header_store_parse(h, val))
else:
newheaders.append((h, v))
self._headers = newheaders
| (self, boundary) |
20,670 | email.message | set_charset | Set the charset of the payload to a given character set.
charset can be a Charset instance, a string naming a character set, or
None. If it is a string it will be converted to a Charset instance.
If charset is None, the charset parameter will be removed from the
Content-Type field. Anything else will generate a TypeError.
The message will be assumed to be of type text/* encoded with
charset.input_charset. It will be converted to charset.output_charset
and encoded properly, if needed, when generating the plain text
representation of the message. MIME headers (MIME-Version,
Content-Type, Content-Transfer-Encoding) will be added as needed.
| def set_charset(self, charset):
"""Set the charset of the payload to a given character set.
charset can be a Charset instance, a string naming a character set, or
None. If it is a string it will be converted to a Charset instance.
If charset is None, the charset parameter will be removed from the
Content-Type field. Anything else will generate a TypeError.
The message will be assumed to be of type text/* encoded with
charset.input_charset. It will be converted to charset.output_charset
and encoded properly, if needed, when generating the plain text
representation of the message. MIME headers (MIME-Version,
Content-Type, Content-Transfer-Encoding) will be added as needed.
"""
if charset is None:
self.del_param('charset')
self._charset = None
return
if not isinstance(charset, Charset):
charset = Charset(charset)
self._charset = charset
if 'MIME-Version' not in self:
self.add_header('MIME-Version', '1.0')
if 'Content-Type' not in self:
self.add_header('Content-Type', 'text/plain',
charset=charset.get_output_charset())
else:
self.set_param('charset', charset.get_output_charset())
if charset != charset.get_output_charset():
self._payload = charset.body_encode(self._payload)
if 'Content-Transfer-Encoding' not in self:
cte = charset.get_body_encoding()
try:
cte(self)
except TypeError:
# This 'if' is for backward compatibility, it allows unicode
# through even though that won't work correctly if the
# message is serialized.
payload = self._payload
if payload:
try:
payload = payload.encode('ascii', 'surrogateescape')
except UnicodeError:
payload = payload.encode(charset.output_charset)
self._payload = charset.body_encode(payload)
self.add_header('Content-Transfer-Encoding', cte)
| (self, charset) |
20,671 | email.message | set_default_type | Set the `default' content type.
ctype should be either "text/plain" or "message/rfc822", although this
is not enforced. The default content type is not stored in the
Content-Type header.
| def set_default_type(self, ctype):
"""Set the `default' content type.
ctype should be either "text/plain" or "message/rfc822", although this
is not enforced. The default content type is not stored in the
Content-Type header.
"""
self._default_type = ctype
| (self, ctype) |
20,672 | email.message | set_param | Set a parameter in the Content-Type header.
If the parameter already exists in the header, its value will be
replaced with the new value.
If header is Content-Type and has not yet been defined for this
message, it will be set to "text/plain" and the new parameter and
value will be appended as per RFC 2045.
An alternate header can be specified in the header argument, and all
parameters will be quoted as necessary unless requote is False.
If charset is specified, the parameter will be encoded according to RFC
2231. Optional language specifies the RFC 2231 language, defaulting
to the empty string. Both charset and language should be strings.
| def set_param(self, param, value, header='Content-Type', requote=True,
charset=None, language='', replace=False):
"""Set a parameter in the Content-Type header.
If the parameter already exists in the header, its value will be
replaced with the new value.
If header is Content-Type and has not yet been defined for this
message, it will be set to "text/plain" and the new parameter and
value will be appended as per RFC 2045.
An alternate header can be specified in the header argument, and all
parameters will be quoted as necessary unless requote is False.
If charset is specified, the parameter will be encoded according to RFC
2231. Optional language specifies the RFC 2231 language, defaulting
to the empty string. Both charset and language should be strings.
"""
if not isinstance(value, tuple) and charset:
value = (charset, language, value)
if header not in self and header.lower() == 'content-type':
ctype = 'text/plain'
else:
ctype = self.get(header)
if not self.get_param(param, header=header):
if not ctype:
ctype = _formatparam(param, value, requote)
else:
ctype = SEMISPACE.join(
[ctype, _formatparam(param, value, requote)])
else:
ctype = ''
for old_param, old_value in self.get_params(header=header,
unquote=requote):
append_param = ''
if old_param.lower() == param.lower():
append_param = _formatparam(param, value, requote)
else:
append_param = _formatparam(old_param, old_value, requote)
if not ctype:
ctype = append_param
else:
ctype = SEMISPACE.join([ctype, append_param])
if ctype != self.get(header):
if replace:
self.replace_header(header, ctype)
else:
del self[header]
self[header] = ctype
| (self, param, value, header='Content-Type', requote=True, charset=None, language='', replace=False) |
20,673 | email.message | set_payload | Set the payload to the given value.
Optional charset sets the message's default character set. See
set_charset() for details.
| def set_payload(self, payload, charset=None):
"""Set the payload to the given value.
Optional charset sets the message's default character set. See
set_charset() for details.
"""
if hasattr(payload, 'encode'):
if charset is None:
self._payload = payload
return
if not isinstance(charset, Charset):
charset = Charset(charset)
payload = payload.encode(charset.output_charset)
if hasattr(payload, 'decode'):
self._payload = payload.decode('ascii', 'surrogateescape')
else:
self._payload = payload
if charset is not None:
self.set_charset(charset)
| (self, payload, charset=None) |
20,674 | email.message | set_raw | Store name and value in the model without modification.
This is an "internal" API, intended only for use by a parser.
| def set_raw(self, name, value):
"""Store name and value in the model without modification.
This is an "internal" API, intended only for use by a parser.
"""
self._headers.append((name, value))
| (self, name, value) |
20,675 | email.message | set_type | Set the main type and subtype for the Content-Type header.
type must be a string in the form "maintype/subtype", otherwise a
ValueError is raised.
This method replaces the Content-Type header, keeping all the
parameters in place. If requote is False, this leaves the existing
header's quoting as is. Otherwise, the parameters will be quoted (the
default).
An alternative header can be specified in the header argument. When
the Content-Type header is set, we'll always also add a MIME-Version
header.
| def set_type(self, type, header='Content-Type', requote=True):
"""Set the main type and subtype for the Content-Type header.
type must be a string in the form "maintype/subtype", otherwise a
ValueError is raised.
This method replaces the Content-Type header, keeping all the
parameters in place. If requote is False, this leaves the existing
header's quoting as is. Otherwise, the parameters will be quoted (the
default).
An alternative header can be specified in the header argument. When
the Content-Type header is set, we'll always also add a MIME-Version
header.
"""
# BAW: should we be strict?
if not type.count('/') == 1:
raise ValueError
# Set the Content-Type, you get a MIME-Version
if header.lower() == 'content-type':
del self['mime-version']
self['MIME-Version'] = '1.0'
if header not in self:
self[header] = type
return
params = self.get_params(header=header, unquote=requote)
del self[header]
self[header] = type
# Skip the first param; it's the old type.
for p, v in params[1:]:
self.set_param(p, v, header, requote)
| (self, type, header='Content-Type', requote=True) |
20,676 | email.message | set_unixfrom | null | def set_unixfrom(self, unixfrom):
self._unixfrom = unixfrom
| (self, unixfrom) |
20,677 | email.message | values | Return a list of all the message's header values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
| def values(self):
"""Return a list of all the message's header values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [self.policy.header_fetch_parse(k, v)
for k, v in self._headers]
| (self) |
20,678 | email.iterators | walk | Walk over the message tree, yielding each subpart.
The walk is performed in depth-first order. This method is a
generator.
| def walk(self):
"""Walk over the message tree, yielding each subpart.
The walk is performed in depth-first order. This method is a
generator.
"""
yield self
if self.is_multipart():
for subpart in self.get_payload():
yield from subpart.walk()
| (self) |
20,679 | http.client | HTTPSConnection | This class allows communication via SSL. | class HTTPSConnection(HTTPConnection):
"This class allows communication via SSL."
default_port = HTTPS_PORT
# XXX Should key_file and cert_file be deprecated in favour of context?
def __init__(self, host, port=None, key_file=None, cert_file=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, *, context=None,
check_hostname=None, blocksize=8192):
super(HTTPSConnection, self).__init__(host, port, timeout,
source_address,
blocksize=blocksize)
if (key_file is not None or cert_file is not None or
check_hostname is not None):
import warnings
warnings.warn("key_file, cert_file and check_hostname are "
"deprecated, use a custom context instead.",
DeprecationWarning, 2)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_default_https_context()
# send ALPN extension to indicate HTTP/1.1 protocol
if self._http_vsn == 11:
context.set_alpn_protocols(['http/1.1'])
# enable PHA for TLS 1.3 connections if available
if context.post_handshake_auth is not None:
context.post_handshake_auth = True
will_verify = context.verify_mode != ssl.CERT_NONE
if check_hostname is None:
check_hostname = context.check_hostname
if check_hostname and not will_verify:
raise ValueError("check_hostname needs a SSL context with "
"either CERT_OPTIONAL or CERT_REQUIRED")
if key_file or cert_file:
context.load_cert_chain(cert_file, key_file)
# cert and key file means the user wants to authenticate.
# enable TLS 1.3 PHA implicitly even for custom contexts.
if context.post_handshake_auth is not None:
context.post_handshake_auth = True
self._context = context
if check_hostname is not None:
self._context.check_hostname = check_hostname
def connect(self):
"Connect to a host on a given (SSL) port."
super().connect()
if self._tunnel_host:
server_hostname = self._tunnel_host
else:
server_hostname = self.host
self.sock = self._context.wrap_socket(self.sock,
server_hostname=server_hostname)
| (host, port=None, key_file=None, cert_file=None, timeout=<object object at 0x7fbc93ea0e50>, source_address=None, *, context=None, check_hostname=None, blocksize=8192) |
20,680 | http.client | __init__ | null | def __init__(self, host, port=None, key_file=None, cert_file=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, *, context=None,
check_hostname=None, blocksize=8192):
super(HTTPSConnection, self).__init__(host, port, timeout,
source_address,
blocksize=blocksize)
if (key_file is not None or cert_file is not None or
check_hostname is not None):
import warnings
warnings.warn("key_file, cert_file and check_hostname are "
"deprecated, use a custom context instead.",
DeprecationWarning, 2)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_default_https_context()
# send ALPN extension to indicate HTTP/1.1 protocol
if self._http_vsn == 11:
context.set_alpn_protocols(['http/1.1'])
# enable PHA for TLS 1.3 connections if available
if context.post_handshake_auth is not None:
context.post_handshake_auth = True
will_verify = context.verify_mode != ssl.CERT_NONE
if check_hostname is None:
check_hostname = context.check_hostname
if check_hostname and not will_verify:
raise ValueError("check_hostname needs a SSL context with "
"either CERT_OPTIONAL or CERT_REQUIRED")
if key_file or cert_file:
context.load_cert_chain(cert_file, key_file)
# cert and key file means the user wants to authenticate.
# enable TLS 1.3 PHA implicitly even for custom contexts.
if context.post_handshake_auth is not None:
context.post_handshake_auth = True
self._context = context
if check_hostname is not None:
self._context.check_hostname = check_hostname
| (self, host, port=None, key_file=None, cert_file=None, timeout=<object object at 0x7fbc93ea0e50>, source_address=None, *, context=None, check_hostname=None, blocksize=8192) |
20,694 | http.client | connect | Connect to a host on a given (SSL) port. | def connect(self):
"Connect to a host on a given (SSL) port."
super().connect()
if self._tunnel_host:
server_hostname = self._tunnel_host
else:
server_hostname = self.host
self.sock = self._context.wrap_socket(self.sock,
server_hostname=server_hostname)
| (self) |
20,703 | mureq | Response | Response contains a completely consumed HTTP response.
:ivar str url: the retrieved URL, indicating whether a redirection occurred
:ivar int status_code: the HTTP status code
:ivar http.client.HTTPMessage headers: the HTTP headers
:ivar bytes body: the payload body of the response
| class Response:
"""Response contains a completely consumed HTTP response.
:ivar str url: the retrieved URL, indicating whether a redirection occurred
:ivar int status_code: the HTTP status code
:ivar http.client.HTTPMessage headers: the HTTP headers
:ivar bytes body: the payload body of the response
"""
__slots__ = ('url', 'status_code', 'headers', 'body')
def __init__(self, url, status_code, headers, body):
self.url, self.status_code, self.headers, self.body = url, status_code, headers, body
def __repr__(self):
return f"Response(status_code={self.status_code:d})"
@property
def ok(self):
"""ok returns whether the response had a successful status code
(anything other than a 40x or 50x)."""
return not (400 <= self.status_code < 600)
@property
def content(self):
"""content returns the response body (the `body` member). This is an
alias for compatibility with requests.Response."""
return self.body
def raise_for_status(self):
"""raise_for_status checks the response's success code, raising an
exception for error codes."""
if not self.ok:
raise HTTPErrorStatus(self.status_code)
def json(self):
"""Attempts to deserialize the response body as UTF-8 encoded JSON."""
import json as jsonlib
return jsonlib.loads(self.body)
def _debugstr(self):
buf = io.StringIO()
print("HTTP", self.status_code, file=buf)
for k, v in self.headers.items():
print(f"{k}: {v}", file=buf)
print(file=buf)
try:
print(self.body.decode('utf-8'), file=buf)
except UnicodeDecodeError:
print(f"<{len(self.body)} bytes binary data>", file=buf)
return buf.getvalue()
| (url, status_code, headers, body) |
20,704 | mureq | __init__ | null | def __init__(self, url, status_code, headers, body):
self.url, self.status_code, self.headers, self.body = url, status_code, headers, body
| (self, url, status_code, headers, body) |
20,705 | mureq | __repr__ | null | def __repr__(self):
return f"Response(status_code={self.status_code:d})"
| (self) |
20,706 | mureq | _debugstr | null | def _debugstr(self):
buf = io.StringIO()
print("HTTP", self.status_code, file=buf)
for k, v in self.headers.items():
print(f"{k}: {v}", file=buf)
print(file=buf)
try:
print(self.body.decode('utf-8'), file=buf)
except UnicodeDecodeError:
print(f"<{len(self.body)} bytes binary data>", file=buf)
return buf.getvalue()
| (self) |
20,707 | mureq | json | Attempts to deserialize the response body as UTF-8 encoded JSON. | def json(self):
"""Attempts to deserialize the response body as UTF-8 encoded JSON."""
import json as jsonlib
return jsonlib.loads(self.body)
| (self) |
20,708 | mureq | raise_for_status | raise_for_status checks the response's success code, raising an
exception for error codes. | def raise_for_status(self):
"""raise_for_status checks the response's success code, raising an
exception for error codes."""
if not self.ok:
raise HTTPErrorStatus(self.status_code)
| (self) |
20,709 | mureq | TooManyRedirects | TooManyRedirects is raised when automatic following of redirects was
enabled, but the server redirected too many times without completing. | class TooManyRedirects(HTTPException):
"""TooManyRedirects is raised when automatic following of redirects was
enabled, but the server redirected too many times without completing."""
pass
| null |
20,710 | mureq | UnixHTTPConnection | UnixHTTPConnection is a subclass of HTTPConnection that connects to a
Unix domain stream socket instead of a TCP address.
| class UnixHTTPConnection(HTTPConnection):
"""UnixHTTPConnection is a subclass of HTTPConnection that connects to a
Unix domain stream socket instead of a TCP address.
"""
def __init__(self, path, timeout=DEFAULT_TIMEOUT):
super(UnixHTTPConnection, self).__init__('localhost', timeout=timeout)
self._unix_path = path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.timeout)
sock.connect(self._unix_path)
except Exception:
sock.close()
raise
self.sock = sock
| (path, timeout=15.0) |
20,711 | mureq | __init__ | null | def __init__(self, path, timeout=DEFAULT_TIMEOUT):
super(UnixHTTPConnection, self).__init__('localhost', timeout=timeout)
self._unix_path = path
| (self, path, timeout=15.0) |
20,725 | mureq | connect | null | def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.timeout)
sock.connect(self._unix_path)
except Exception:
sock.close()
raise
self.sock = sock
| (self) |
20,734 | mureq | _check_redirect | Return the URL to redirect to, or None for no redirection. | def _check_redirect(url, status, response_headers):
"""Return the URL to redirect to, or None for no redirection."""
if status not in (301, 302, 303, 307, 308):
return None
location = response_headers.get('Location')
if not location:
return None
parsed_location = urllib.parse.urlparse(location)
if parsed_location.scheme:
# absolute URL
return location
old_url = urllib.parse.urlparse(url)
if location.startswith('/'):
# absolute path on old hostname
return urllib.parse.urlunparse((old_url.scheme, old_url.netloc,
parsed_location.path, parsed_location.params,
parsed_location.query, parsed_location.fragment))
# relative path on old hostname
old_dir, _old_file = os.path.split(old_url.path)
new_path = os.path.join(old_dir, location)
return urllib.parse.urlunparse((old_url.scheme, old_url.netloc,
new_path, parsed_location.params,
parsed_location.query, parsed_location.fragment))
| (url, status, response_headers) |
20,735 | mureq | _prepare_body | null | def _prepare_body(body, form, json, headers):
if body is not None:
if not isinstance(body, bytes):
raise TypeError('body must be bytes or None', type(body))
return body
if json is not None:
_setdefault_header(headers, 'Content-Type', _JSON_CONTENTTYPE)
import json as jsonlib
return jsonlib.dumps(json).encode('utf-8')
if form is not None:
_setdefault_header(headers, 'Content-Type', _FORM_CONTENTTYPE)
return urllib.parse.urlencode(form, doseq=True)
return None
| (body, form, json, headers) |
20,736 | mureq | _prepare_incoming_headers | null | def _prepare_incoming_headers(headers):
headers_dict = {}
for k, v in headers.items():
headers_dict.setdefault(k, []).append(v)
result = HTTPMessage()
# note that iterating over headers_dict preserves the original
# insertion order in all versions since Python 3.6:
for k, vlist in headers_dict.items():
result[k] = ','.join(vlist)
return result
| (headers) |
20,737 | mureq | _prepare_outgoing_headers | null | def _prepare_outgoing_headers(headers):
if headers is None:
headers = HTTPMessage()
elif not isinstance(headers, HTTPMessage):
new_headers = HTTPMessage()
if hasattr(headers, 'items'):
iterator = headers.items()
else:
iterator = iter(headers)
for k, v in iterator:
new_headers[k] = v
headers = new_headers
_setdefault_header(headers, 'User-Agent', DEFAULT_UA)
return headers
| (headers) |
20,738 | mureq | _prepare_params | null | def _prepare_params(params):
if params is None:
return ''
return urllib.parse.urlencode(params, doseq=True)
| (params) |
20,739 | mureq | _prepare_request | Parses the URL, returns the path and the right HTTPConnection subclass. | def _prepare_request(method, url, *, enc_params='', timeout=DEFAULT_TIMEOUT, source_address=None, unix_socket=None, verify=True, ssl_context=None):
"""Parses the URL, returns the path and the right HTTPConnection subclass."""
parsed_url = urllib.parse.urlparse(url)
is_unix = (unix_socket is not None)
scheme = parsed_url.scheme.lower()
if scheme.endswith('+unix'):
scheme = scheme[:-5]
is_unix = True
if scheme == 'https':
raise ValueError("https+unix is not implemented")
if scheme not in ('http', 'https'):
raise ValueError("unrecognized scheme", scheme)
is_https = (scheme == 'https')
host = parsed_url.hostname
port = 443 if is_https else 80
if parsed_url.port:
port = parsed_url.port
if is_unix and unix_socket is None:
unix_socket = urllib.parse.unquote(parsed_url.netloc)
path = parsed_url.path
if parsed_url.query:
if enc_params:
path = f'{path}?{parsed_url.query}&{enc_params}'
else:
path = f'{path}?{parsed_url.query}'
else:
if enc_params:
path = f'{path}?{enc_params}'
else:
pass # just parsed_url.path in this case
if isinstance(source_address, str):
source_address = (source_address, 0)
if is_unix:
conn = UnixHTTPConnection(unix_socket, timeout=timeout)
elif is_https:
if ssl_context is None:
ssl_context = ssl.create_default_context()
if not verify:
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
conn = HTTPSConnection(host, port, source_address=source_address, timeout=timeout,
context=ssl_context)
else:
conn = HTTPConnection(host, port, source_address=source_address, timeout=timeout)
munged_url = urllib.parse.urlunparse((parsed_url.scheme, parsed_url.netloc,
path, parsed_url.params,
'', parsed_url.fragment))
return munged_url, conn, path
| (method, url, *, enc_params='', timeout=15.0, source_address=None, unix_socket=None, verify=True, ssl_context=None) |
20,740 | mureq | _setdefault_header | null | def _setdefault_header(headers, name, value):
if name not in headers:
headers[name] = value
| (headers, name, value) |
20,742 | mureq | delete | delete performs an HTTP DELETE request. | def delete(url, **kwargs):
"""delete performs an HTTP DELETE request."""
return request('DELETE', url=url, **kwargs)
| (url, **kwargs) |
20,743 | mureq | get | get performs an HTTP GET request. | def get(url, **kwargs):
"""get performs an HTTP GET request."""
return request('GET', url=url, **kwargs)
| (url, **kwargs) |
20,744 | mureq | head | head performs an HTTP HEAD request. | def head(url, **kwargs):
"""head performs an HTTP HEAD request."""
return request('HEAD', url=url, **kwargs)
| (url, **kwargs) |
20,747 | mureq | patch | patch performs an HTTP PATCH request. | def patch(url, body=None, **kwargs):
"""patch performs an HTTP PATCH request."""
return request('PATCH', url=url, body=body, **kwargs)
| (url, body=None, **kwargs) |
20,748 | mureq | post | post performs an HTTP POST request. | def post(url, body=None, **kwargs):
"""post performs an HTTP POST request."""
return request('POST', url=url, body=body, **kwargs)
| (url, body=None, **kwargs) |
20,749 | mureq | put | put performs an HTTP PUT request. | def put(url, body=None, **kwargs):
"""put performs an HTTP PUT request."""
return request('PUT', url=url, body=body, **kwargs)
| (url, body=None, **kwargs) |
20,750 | mureq | request | request performs an HTTP request and reads the entire response body.
:param str method: HTTP method to request (e.g. 'GET', 'POST')
:param str url: URL to request
:param read_limit: maximum number of bytes to read from the body, or None for no limit
:type read_limit: int or None
:param kwargs: optional arguments defined by yield_response
:return: Response object
:rtype: Response
:raises: HTTPException
| def request(method, url, *, read_limit=None, **kwargs):
"""request performs an HTTP request and reads the entire response body.
:param str method: HTTP method to request (e.g. 'GET', 'POST')
:param str url: URL to request
:param read_limit: maximum number of bytes to read from the body, or None for no limit
:type read_limit: int or None
:param kwargs: optional arguments defined by yield_response
:return: Response object
:rtype: Response
:raises: HTTPException
"""
with yield_response(method, url, **kwargs) as response:
try:
body = response.read(read_limit)
except HTTPException:
raise
except IOError as e:
raise HTTPException(str(e)) from e
return Response(response.url, response.status, _prepare_incoming_headers(response.headers), body)
| (method, url, *, read_limit=None, **kwargs) |
20,755 | mureq | yield_response | yield_response is a low-level API that exposes the actual
http.client.HTTPResponse via a contextmanager.
Note that unlike mureq.Response, http.client.HTTPResponse does not
automatically canonicalize multiple appearances of the same header by
joining them together with a comma delimiter. To retrieve canonicalized
headers from the response, use response.getheader():
https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse.getheader
:param str method: HTTP method to request (e.g. 'GET', 'POST')
:param str url: URL to request
:param unix_socket: path to Unix domain socket to query, or None for a normal TCP request
:type unix_socket: str or None
:param timeout: timeout in seconds, or None for no timeout (default: 15 seconds)
:type timeout: float or None
:param headers: HTTP headers as a mapping or list of key-value pairs
:param params: parameters to be URL-encoded and added to the query string, as a mapping or list of key-value pairs
:param body: payload body of the request
:type body: bytes or None
:param form: parameters to be form-encoded and sent as the payload body, as a mapping or list of key-value pairs
:param json: object to be serialized as JSON and sent as the payload body
:param bool verify: whether to verify TLS certificates (default: True)
:param source_address: source address to bind to for TCP
:type source_address: str or tuple(str, int) or None
:param max_redirects: maximum number of redirects to follow, or None (the default) for no redirection
:type max_redirects: int or None
:param ssl_context: TLS config to control certificate validation, or None for default behavior
:type ssl_context: ssl.SSLContext or None
:return: http.client.HTTPResponse, yielded as context manager
:rtype: http.client.HTTPResponse
:raises: HTTPException
| def _prepare_outgoing_headers(headers):
if headers is None:
headers = HTTPMessage()
elif not isinstance(headers, HTTPMessage):
new_headers = HTTPMessage()
if hasattr(headers, 'items'):
iterator = headers.items()
else:
iterator = iter(headers)
for k, v in iterator:
new_headers[k] = v
headers = new_headers
_setdefault_header(headers, 'User-Agent', DEFAULT_UA)
return headers
| (method, url, *, unix_socket=None, timeout=15.0, headers=None, params=None, body=None, form=None, json=None, verify=True, source_address=None, max_redirects=None, ssl_context=None) |
20,756 | builtins | mappingproxy | null | from builtins import mappingproxy
| null |
20,757 | prettyprinter | PrettyPrinter | null | class PrettyPrinter:
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
def pprint(self, object):
pprint(*self._args, **self._kwargs)
def pformat(self, object):
return pformat(*self._args, **self._kwargs)
def isrecursive(self, object):
return isrecursive(object)
def isreadable(self, object):
return isreadable(object)
def format(self, object):
raise NotImplementedError
| (*args, **kwargs) |
20,758 | prettyprinter | __init__ | null | def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
| (self, *args, **kwargs) |
20,759 | prettyprinter | format | null | def format(self, object):
raise NotImplementedError
| (self, object) |
20,760 | prettyprinter | isreadable | null | def isreadable(self, object):
return isreadable(object)
| (self, object) |
20,761 | prettyprinter | isrecursive | null | def isrecursive(self, object):
return isrecursive(object)
| (self, object) |
20,762 | prettyprinter | pformat | null | def pformat(self, object):
return pformat(*self._args, **self._kwargs)
| (self, object) |
20,763 | prettyprinter | pprint | null | def pprint(self, object):
pprint(*self._args, **self._kwargs)
| (self, object) |
20,765 | prettyprinter | UnsetSentinel | null | class UnsetSentinel:
def __repr__(self):
return 'UNSET'
__str__ = __repr__
| () |
20,766 | prettyprinter | __repr__ | null | def __repr__(self):
return 'UNSET'
| (self) |
20,768 | prettyprinter | _merge_defaults | null | def _merge_defaults(
*, indent, width, depth, ribbon_width, max_seq_len, sort_dict_keys
):
kwargs = locals()
return {key: kwargs[key] if kwargs[key] is not _UNSET_SENTINEL else default
for key, default in _default_config.items()}
| (*, indent, width, depth, ribbon_width, max_seq_len, sort_dict_keys) |
20,770 | prettyprinter.color | colored_render_to_stream | null | def colored_render_to_stream(
stream,
sdocs,
style,
newline='\n',
separator=' '
):
if style is None:
style = default_style
evald = list(sdocs)
if not evald:
return
color_cache = {}
colorstack = []
sdoc_lines = as_lines(evald)
for sdoc_line in sdoc_lines:
last_text_sdoc_idx = rfind_idx(
lambda sdoc: isinstance(sdoc, str),
sdoc_line
)
# Edge case: trailing whitespace on a line.
# Currently happens on multiline str value in a dict:
# there's a trailing whitespace after the colon that's
# hard to eliminate at the doc level.
if last_text_sdoc_idx != -1:
last_text_sdoc = sdoc_line[last_text_sdoc_idx]
sdoc_line[last_text_sdoc_idx] = last_text_sdoc.rstrip()
for sdoc in sdoc_line:
if isinstance(sdoc, str):
stream.write(sdoc)
elif isinstance(sdoc, SLine):
stream.write(newline + separator * sdoc.indent)
elif isinstance(sdoc, SAnnotationPush):
if isinstance(sdoc.value, Token):
try:
color = color_cache[sdoc.value]
except KeyError:
pygments_token = _SYNTAX_TOKEN_TO_PYGMENTS_TOKEN[
sdoc.value
]
tokenattrs = style.style_for_token(pygments_token)
color = styleattrs_to_colorful(tokenattrs)
color_cache[sdoc.value] = color
colorstack.append(color)
stream.write(str(color))
elif isinstance(sdoc, SAnnotationPop):
try:
colorstack.pop()
except IndexError:
continue
if colorstack:
stream.write(str(colorstack[-1]))
else:
stream.write(str(colorful.reset))
if colorstack:
stream.write(str(colorful.reset))
| (stream, sdocs, style, newline='\n', separator=' ') |
20,771 | prettyprinter.prettyprinter | comment | Annotates a value or a Doc with a comment.
When printed by prettyprinter, the comment will be
rendered next to the value or Doc.
| def comment(value, comment_text):
"""Annotates a value or a Doc with a comment.
When printed by prettyprinter, the comment will be
rendered next to the value or Doc.
"""
if isinstance(value, Doc):
return comment_doc(value, comment_text)
return comment_value(value, comment_text)
| (value, comment_text) |
20,772 | prettyprinter | cpprint | Pretty print a Python value ``object`` to ``stream``,
which defaults to sys.stdout. The output will be colored and
syntax highlighted.
:param indent: number of spaces to add for each level of nesting.
:param stream: the output stream, defaults to sys.stdout
:param width: a soft maximum allowed number of columns in the output,
which the layout algorithm attempts to stay under.
:param depth: maximum depth to print nested structures
:param ribbon_width: a soft maximum allowed number of columns in the output,
after indenting the line
:param max_seq_len: a maximum sequence length that applies to subclasses of
lists, sets, frozensets, tuples and dicts. A trailing
comment that indicates the number of truncated elements.
Setting max_seq_len to ``None`` disables truncation.
:param sort_dict_keys: a ``bool`` value indicating if dict keys should be
sorted in the output. Defaults to ``False``, in
which case the default order is used, which is the
insertion order in CPython 3.6+.
:param style: one of ``'light'``, ``'dark'`` or a subclass
of ``pygments.styles.Style``. If omitted,
will use the default style. If the default style
is not changed by the user with :func:`~prettyprinter.set_default_style`,
the default is ``'dark'``.
| def cpprint(
object,
stream=_UNSET_SENTINEL,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
compact=False,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL,
style=None,
end='\n'
):
"""Pretty print a Python value ``object`` to ``stream``,
which defaults to sys.stdout. The output will be colored and
syntax highlighted.
:param indent: number of spaces to add for each level of nesting.
:param stream: the output stream, defaults to sys.stdout
:param width: a soft maximum allowed number of columns in the output,
which the layout algorithm attempts to stay under.
:param depth: maximum depth to print nested structures
:param ribbon_width: a soft maximum allowed number of columns in the output,
after indenting the line
:param max_seq_len: a maximum sequence length that applies to subclasses of
lists, sets, frozensets, tuples and dicts. A trailing
comment that indicates the number of truncated elements.
Setting max_seq_len to ``None`` disables truncation.
:param sort_dict_keys: a ``bool`` value indicating if dict keys should be
sorted in the output. Defaults to ``False``, in
which case the default order is used, which is the
insertion order in CPython 3.6+.
:param style: one of ``'light'``, ``'dark'`` or a subclass
of ``pygments.styles.Style``. If omitted,
will use the default style. If the default style
is not changed by the user with :func:`~prettyprinter.set_default_style`,
the default is ``'dark'``.
"""
sdocs = python_to_sdocs(
object,
**_merge_defaults(
indent=indent,
width=width,
depth=depth,
ribbon_width=ribbon_width,
max_seq_len=max_seq_len,
sort_dict_keys=sort_dict_keys,
)
)
stream = (
# This is not in _default_config in case
# sys.stdout changes.
sys.stdout
if stream is _UNSET_SENTINEL
else stream
)
colored_render_to_stream(stream, sdocs, style=style)
if end:
stream.write(end)
| (object, stream=UNSET, indent=UNSET, width=UNSET, depth=UNSET, *, compact=False, ribbon_width=UNSET, max_seq_len=UNSET, sort_dict_keys=UNSET, style=None, end='\n') |
20,773 | prettyprinter.render | default_render_to_stream | null | def default_render_to_stream(stream, sdocs, newline='\n', separator=' '):
evald = list(sdocs)
if not evald:
return
for sdoc_line in as_lines(evald):
last_text_sdoc_idx = rfind_idx(
lambda sdoc: isinstance(sdoc, str),
sdoc_line
)
# Edge case: trailing whitespace on a line.
# Currently happens on multiline str value in a dict:
# there's a trailing whitespace after the colon that's
# hard to eliminate at the doc level.
if last_text_sdoc_idx != -1:
last_text_sdoc = sdoc_line[last_text_sdoc_idx]
sdoc_line[last_text_sdoc_idx] = last_text_sdoc.rstrip()
for sdoc in sdoc_line:
if isinstance(sdoc, str):
stream.write(sdoc)
elif isinstance(sdoc, SLine):
stream.write(newline + separator * sdoc.indent)
| (stream, sdocs, newline='\n', separator=' ') |
20,776 | prettyprinter | get_default_config | Returns a read-only view of the current configuration | def get_default_config():
"""Returns a read-only view of the current configuration"""
return MappingProxyType(_default_config)
| () |
20,777 | importlib | import_module | Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
| def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
level = 0
if name.startswith('.'):
if not package:
msg = ("the 'package' argument is required to perform a relative "
"import for {!r}")
raise TypeError(msg.format(name))
for character in name:
if character != '.':
break
level += 1
return _bootstrap._gcd_import(name[level:], package, level)
| (name, package=None) |
20,778 | prettyprinter | install_extras | Installs extras.
Installing an extra means registering pretty printers for objects from third
party libraries and/or enabling integrations with other python programs.
- ``'attrs'`` - automatically pretty prints classes created using the ``attrs`` package.
- ``'dataclasses'`` - automatically pretty prints classes created using the ``dataclasses``
module.
- ``'django'`` - automatically pretty prints Model and QuerySet subclasses defined in your
Django apps.
- ``numpy`` - automatically pretty prints numpy scalars with explicit types, and,
for numpy>=1.14, numpy arrays.
- ``'requests'`` - automatically pretty prints Requests, Responses, Sessions, etc.
- ``'ipython'`` - makes prettyprinter the default printer in the IPython shell.
- ``'python'`` - makes prettyprinter the default printer in the default Python shell.
- ``'ipython_repr_pretty'`` - automatically prints objects that define a ``_repr_pretty_``
method to integrate with `IPython.lib.pretty
<http://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html#extending>`_.
:param include: an iterable of strs representing the extras to include.
All extras are included by default.
:param exclude: an iterable of strs representing the extras to exclude.
| def install_extras(
include=ALL_EXTRAS,
*,
exclude=EMPTY_SET,
raise_on_error=False,
warn_on_error=True
):
"""Installs extras.
Installing an extra means registering pretty printers for objects from third
party libraries and/or enabling integrations with other python programs.
- ``'attrs'`` - automatically pretty prints classes created using the ``attrs`` package.
- ``'dataclasses'`` - automatically pretty prints classes created using the ``dataclasses``
module.
- ``'django'`` - automatically pretty prints Model and QuerySet subclasses defined in your
Django apps.
- ``numpy`` - automatically pretty prints numpy scalars with explicit types, and,
for numpy>=1.14, numpy arrays.
- ``'requests'`` - automatically pretty prints Requests, Responses, Sessions, etc.
- ``'ipython'`` - makes prettyprinter the default printer in the IPython shell.
- ``'python'`` - makes prettyprinter the default printer in the default Python shell.
- ``'ipython_repr_pretty'`` - automatically prints objects that define a ``_repr_pretty_``
method to integrate with `IPython.lib.pretty
<http://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html#extending>`_.
:param include: an iterable of strs representing the extras to include.
All extras are included by default.
:param exclude: an iterable of strs representing the extras to exclude.
""" # noqa
include = set(include)
exclude = set(exclude)
unexisting_extras = (include | exclude) - ALL_EXTRAS
if unexisting_extras:
raise ValueError(
"The following extras don't exist: {}".format(
', '.join(unexisting_extras)
)
)
extras_to_install = (ALL_EXTRAS & include) - exclude
for extra in extras_to_install:
module_name = 'prettyprinter.extras.' + extra
try:
extra_module = import_module(module_name)
except ImportError as e:
if raise_on_error:
raise e
if warn_on_error:
warnings.warn(
"Failed to import '{0}' PrettyPrinter extra. "
"If you don't need it, call install_extras with "
"exclude=['{0}']".format(extra)
)
else:
try:
extra_module.install()
except Exception as exc:
if raise_on_error:
raise exc
elif warn_on_error:
warnings.warn(
"Failed to install '{0}' PrettyPrinter extra. "
"If you don't need it, call install_extras with "
"exclude=['{0}']".format(extra)
)
| (include=frozenset({'python', 'numpy', 'attrs', 'ipython_repr_pretty', 'ipython', 'requests', 'dataclasses', 'django'}), *, exclude=frozenset(), raise_on_error=False, warn_on_error=True) |
20,779 | prettyprinter.prettyprinter | is_registered | null | def is_registered(
type,
*,
check_superclasses=False,
check_deferred=True,
register_deferred=True
):
if not check_deferred and register_deferred:
raise ValueError(
'register_deferred may not be True when check_deferred is False'
)
if type in pretty_dispatch.registry:
return True
if check_deferred:
# Check deferred printers for the type exactly.
deferred_key = get_deferred_key(type)
if deferred_key in _DEFERRED_DISPATCH_BY_NAME:
if register_deferred:
deferred_dispatch = _DEFERRED_DISPATCH_BY_NAME.pop(
deferred_key
)
register_pretty(type)(deferred_dispatch)
return True
if not check_superclasses:
return False
if check_deferred:
# Check deferred printers for supertypes.
for supertype in type.__mro__[1:]:
deferred_key = get_deferred_key(supertype)
if deferred_key in _DEFERRED_DISPATCH_BY_NAME:
if register_deferred:
deferred_dispatch = _DEFERRED_DISPATCH_BY_NAME.pop(
deferred_key
)
register_pretty(supertype)(deferred_dispatch)
return True
return pretty_dispatch.dispatch(type) is not _BASE_DISPATCH
| (type, *, check_superclasses=False, check_deferred=True, register_deferred=True) |
20,780 | pprint | isreadable | Determine if saferepr(object) is readable by eval(). | def isreadable(object):
"""Determine if saferepr(object) is readable by eval()."""
return PrettyPrinter()._safe_repr(object, {}, None, 0)[1]
| (object) |
20,781 | pprint | isrecursive | Determine if object requires a recursive representation. | def isrecursive(object):
"""Determine if object requires a recursive representation."""
return PrettyPrinter()._safe_repr(object, {}, None, 0)[2]
| (object) |
20,783 | prettyprinter | pformat |
Returns a pretty printed representation of the object as a ``str``.
Accepts the same parameters as :func:`~prettyprinter.pprint`.
The output is not colored.
| def pformat(
object,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
compact=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL
):
"""
Returns a pretty printed representation of the object as a ``str``.
Accepts the same parameters as :func:`~prettyprinter.pprint`.
The output is not colored.
"""
sdocs = python_to_sdocs(
object,
**_merge_defaults(
indent=indent,
width=width,
depth=depth,
ribbon_width=ribbon_width,
max_seq_len=max_seq_len,
sort_dict_keys=sort_dict_keys,
)
)
stream = StringIO()
default_render_to_stream(stream, sdocs)
return stream.getvalue()
| (object, indent=UNSET, width=UNSET, depth=UNSET, *, ribbon_width=UNSET, max_seq_len=UNSET, compact=UNSET, sort_dict_keys=UNSET) |
20,784 | prettyprinter | pprint | Pretty print a Python value ``object`` to ``stream``,
which defaults to ``sys.stdout``. The output will not be colored.
:param indent: number of spaces to add for each level of nesting.
:param stream: the output stream, defaults to ``sys.stdout``
:param width: a soft maximum allowed number of columns in the output,
which the layout algorithm attempts to stay under.
:param depth: maximum depth to print nested structures
:param ribbon_width: a soft maximum allowed number of columns in the output,
after indenting the line
:param max_seq_len: a maximum sequence length that applies to subclasses of
lists, sets, frozensets, tuples and dicts. A trailing
comment that indicates the number of truncated elements.
Setting max_seq_len to ``None`` disables truncation.
:param sort_dict_keys: a ``bool`` value indicating if dict keys should be
sorted in the output. Defaults to ``False``, in
which case the default order is used, which is the
insertion order in CPython 3.6+.
| def pprint(
object,
stream=_UNSET_SENTINEL,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
compact=False,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL,
end='\n'
):
"""Pretty print a Python value ``object`` to ``stream``,
which defaults to ``sys.stdout``. The output will not be colored.
:param indent: number of spaces to add for each level of nesting.
:param stream: the output stream, defaults to ``sys.stdout``
:param width: a soft maximum allowed number of columns in the output,
which the layout algorithm attempts to stay under.
:param depth: maximum depth to print nested structures
:param ribbon_width: a soft maximum allowed number of columns in the output,
after indenting the line
:param max_seq_len: a maximum sequence length that applies to subclasses of
lists, sets, frozensets, tuples and dicts. A trailing
comment that indicates the number of truncated elements.
Setting max_seq_len to ``None`` disables truncation.
:param sort_dict_keys: a ``bool`` value indicating if dict keys should be
sorted in the output. Defaults to ``False``, in
which case the default order is used, which is the
insertion order in CPython 3.6+.
"""
sdocs = python_to_sdocs(
object,
**_merge_defaults(
indent=indent,
width=width,
depth=depth,
ribbon_width=ribbon_width,
max_seq_len=max_seq_len,
sort_dict_keys=sort_dict_keys,
)
)
stream = (
# This is not in _default_config in case
# sys.stdout changes.
sys.stdout
if stream is _UNSET_SENTINEL
else stream
)
default_render_to_stream(stream, sdocs)
if end:
stream.write(end)
| (object, stream=UNSET, indent=UNSET, width=UNSET, depth=UNSET, *, compact=False, ribbon_width=UNSET, max_seq_len=UNSET, sort_dict_keys=UNSET, end='\n') |
20,785 | prettyprinter.prettyprinter | pretty_call | Returns a Doc that represents a function call to :keyword:`fn` with
the remaining positional and keyword arguments.
You can only use this function on Python 3.6+. On Python 3.5, the order
of keyword arguments is not maintained, and you have to use
:func:`~prettyprinter.pretty_call_alt`.
Given an arbitrary context ``ctx``,::
pretty_call(ctx, sorted, [7, 4, 5], reverse=True)
Will result in output::
sorted([7, 4, 5], reverse=True)
The layout algorithm will automatically break the call to multiple
lines if needed::
sorted(
[7, 4, 5],
reverse=True
)
``pretty_call`` automatically handles syntax highlighting.
:param ctx: a context value
:type ctx: prettyprinter.prettyprinter.PrettyContext
:param fn: a callable
:param args: positional arguments to render to the call
:param kwargs: keyword arguments to render to the call
:returns: :class:`~prettyprinter.doc.Doc`
| def pretty_call(ctx, fn, *args, **kwargs):
"""Returns a Doc that represents a function call to :keyword:`fn` with
the remaining positional and keyword arguments.
You can only use this function on Python 3.6+. On Python 3.5, the order
of keyword arguments is not maintained, and you have to use
:func:`~prettyprinter.pretty_call_alt`.
Given an arbitrary context ``ctx``,::
pretty_call(ctx, sorted, [7, 4, 5], reverse=True)
Will result in output::
sorted([7, 4, 5], reverse=True)
The layout algorithm will automatically break the call to multiple
lines if needed::
sorted(
[7, 4, 5],
reverse=True
)
``pretty_call`` automatically handles syntax highlighting.
:param ctx: a context value
:type ctx: prettyprinter.prettyprinter.PrettyContext
:param fn: a callable
:param args: positional arguments to render to the call
:param kwargs: keyword arguments to render to the call
:returns: :class:`~prettyprinter.doc.Doc`
"""
return pretty_call_alt(ctx, fn, args, kwargs)
| (ctx, fn, *args, **kwargs) |
20,786 | prettyprinter.prettyprinter | pretty_call_alt | Returns a Doc that represents a function call to :keyword:`fn` with
the ``args`` and ``kwargs``.
Given an arbitrary context ``ctx``,::
pretty_call_alt(ctx, sorted, args=([7, 4, 5], ), kwargs=[('reverse', True)])
Will result in output::
sorted([7, 4, 5], reverse=True)
The layout algorithm will automatically break the call to multiple
lines if needed::
sorted(
[7, 4, 5],
reverse=True
)
``pretty_call_alt`` automatically handles syntax highlighting.
:param ctx: a context value
:type ctx: prettyprinter.prettyprinter.PrettyContext
:param fn: a callable
:param args: a ``tuple`` of positional arguments to render to the call
:param kwargs: keyword arguments to render to the call. Either an instance
of ``OrderedDict``, or an iterable of two-tuples, where the
first element is a `str` (key), and the second is the Python
value for that keyword argument.
:returns: :class:`~prettyprinter.doc.Doc`
| def pretty_call_alt(ctx, fn, args=(), kwargs=()):
"""Returns a Doc that represents a function call to :keyword:`fn` with
the ``args`` and ``kwargs``.
Given an arbitrary context ``ctx``,::
pretty_call_alt(ctx, sorted, args=([7, 4, 5], ), kwargs=[('reverse', True)])
Will result in output::
sorted([7, 4, 5], reverse=True)
The layout algorithm will automatically break the call to multiple
lines if needed::
sorted(
[7, 4, 5],
reverse=True
)
``pretty_call_alt`` automatically handles syntax highlighting.
:param ctx: a context value
:type ctx: prettyprinter.prettyprinter.PrettyContext
:param fn: a callable
:param args: a ``tuple`` of positional arguments to render to the call
:param kwargs: keyword arguments to render to the call. Either an instance
of ``OrderedDict``, or an iterable of two-tuples, where the
first element is a `str` (key), and the second is the Python
value for that keyword argument.
:returns: :class:`~prettyprinter.doc.Doc`
"""
fndoc = general_identifier(fn)
if ctx.depth_left <= 0:
return concat([fndoc, LPAREN, ELLIPSIS, RPAREN])
if not kwargs and len(args) == 1:
sole_arg = args[0]
unwrapped_sole_arg, _comment, _trailing_comment = unwrap_comments(args[0])
if type(unwrapped_sole_arg) in (list, dict, tuple):
return build_fncall(
ctx,
fndoc,
argdocs=[pretty_python_value(sole_arg, ctx)],
hug_sole_arg=True,
)
nested_ctx = (
ctx
.nested_call()
.use_multiline_strategy(MULTILINE_STRATEGY_HANG)
)
if not DICT_KEY_ORDER_SUPPORTED and isinstance(kwargs, dict):
warnings.warn(
"A dict was passed to pretty_call_alt to represent kwargs, "
"but Python 3.5 doesn't maintain key order for dicts. The order "
"of keyword arguments will be undefined in the output. "
"To fix this, pass a list of two-tuples or an instance of "
"OrderedDict instead.",
UserWarning
)
kwargitems = (
kwargs.items()
if isinstance(kwargs, (OrderedDict, dict))
else kwargs
)
return build_fncall(
ctx,
fndoc,
argdocs=(
pretty_python_value(arg, nested_ctx)
for arg in args
),
kwargdocs=(
(kwarg, pretty_python_value(v, nested_ctx))
for kwarg, v in kwargitems
),
)
| (ctx, fn, args=(), kwargs=()) |
20,787 | prettyprinter | pretty_repr |
A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
__repr__ = pretty_repr
| def pretty_repr(instance):
"""
A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
__repr__ = pretty_repr
"""
instance_type = type(instance)
if not is_registered(
instance_type,
check_superclasses=True,
check_deferred=True,
register_deferred=True
):
warnings.warn(
"pretty_repr is assigned as the __repr__ method of "
"'{}'. However, no pretty printer is registered for that type, "
"its superclasses or its subclasses. Falling back to the default "
"repr implementation. To fix this warning, register a pretty "
"printer using prettyprinter.register_pretty.".format(
instance_type.__qualname__
),
UserWarning
)
return object.__repr__(instance)
return pformat(instance)
| (instance) |
20,790 | prettyprinter.prettyprinter | python_to_sdocs | null | def python_to_sdocs(
value,
indent,
width,
depth,
ribbon_width,
max_seq_len,
sort_dict_keys
):
if depth is None:
depth = float('inf')
doc = pretty_python_value(
value,
ctx=PrettyContext(
indent=indent,
depth_left=depth,
visited=set(),
max_seq_len=max_seq_len,
sort_dict_keys=sort_dict_keys
)
)
if is_commented(doc):
doc = group(
flat_choice(
when_flat=concat([
doc,
' ',
commentdoc(doc.annotation.value),
]),
when_broken=concat([
commentdoc(doc.annotation.value),
HARDLINE,
doc
])
)
)
ribbon_frac = min(1.0, ribbon_width / width)
return layout_smart(doc, width=width, ribbon_frac=ribbon_frac)
| (value, indent, width, depth, ribbon_width, max_seq_len, sort_dict_keys) |
20,791 | prettyprinter.prettyprinter | register_pretty | Returns a decorator that registers the decorated function
as the pretty printer for instances of ``type``.
:param type: the type to register the pretty printer for, or a ``str``
to indicate the module and name, e.g.: ``'collections.Counter'``.
:param predicate: a predicate function that takes one argument
and returns a boolean indicating if the value
should be handled by the registered pretty printer.
Only one of ``type`` and ``predicate`` may be supplied. That means
that ``predicate`` will be run on unregistered types only.
The decorated function must accept exactly two positional arguments:
- ``value`` to pretty print, and
- ``ctx``, a context value.
Here's an example of the pretty printer for OrderedDict:
.. code:: python
from collections import OrderedDict
from prettyprinter import register_pretty, pretty_call
@register_pretty(OrderedDict)
def pretty_orderreddict(value, ctx):
return pretty_call(ctx, OrderedDict, list(value.items()))
| def register_pretty(type=None, predicate=None):
"""Returns a decorator that registers the decorated function
as the pretty printer for instances of ``type``.
:param type: the type to register the pretty printer for, or a ``str``
to indicate the module and name, e.g.: ``'collections.Counter'``.
:param predicate: a predicate function that takes one argument
and returns a boolean indicating if the value
should be handled by the registered pretty printer.
Only one of ``type`` and ``predicate`` may be supplied. That means
that ``predicate`` will be run on unregistered types only.
The decorated function must accept exactly two positional arguments:
- ``value`` to pretty print, and
- ``ctx``, a context value.
Here's an example of the pretty printer for OrderedDict:
.. code:: python
from collections import OrderedDict
from prettyprinter import register_pretty, pretty_call
@register_pretty(OrderedDict)
def pretty_orderreddict(value, ctx):
return pretty_call(ctx, OrderedDict, list(value.items()))
"""
if type is None and predicate is None:
raise ValueError(
"You must provide either the 'type' or 'predicate' argument."
)
if type is not None and predicate is not None:
raise ValueError(
"You must provide either the 'type' or 'predicate' argument,"
"but not both"
)
if predicate is not None:
if not callable(predicate):
raise ValueError(
"Expected a callable for 'predicate', got {}".format(
repr(predicate)
)
)
def decorator(fn):
sig = inspect.signature(fn)
value = None
ctx = None
try:
sig.bind(value, ctx)
except TypeError:
fnname = '{}.{}'.format(
fn.__module__,
fn.__qualname__
)
raise ValueError(
"Functions decorated with register_pretty must accept "
"exactly two positional parameters: 'value' and 'ctx'. "
"The function signature for {} was not compatible.".format(
fnname
)
)
if type:
if isinstance(type, str):
# We don't wrap this with _run_pretty,
# so that when we register this printer with an actual
# class, we can call register_pretty(cls)(fn)
_DEFERRED_DISPATCH_BY_NAME[type] = fn
else:
pretty_dispatch.register(type, partial(_run_pretty, fn))
else:
assert callable(predicate)
_PREDICATE_REGISTRY.append((predicate, fn))
return fn
return decorator
| (type=None, predicate=None) |
20,793 | pprint | saferepr | Version of repr() which can handle recursive data structures. | def saferepr(object):
"""Version of repr() which can handle recursive data structures."""
return PrettyPrinter()._safe_repr(object, {}, None, 0)[0]
| (object) |
20,795 | prettyprinter | set_default_config |
Sets the default configuration values used when calling
`pprint`, `cpprint`, or `pformat`, if those values weren't
explicitly provided. Only overrides the values provided in
the keyword arguments.
| def set_default_config(
*,
style=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
ribbon_width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL
):
"""
Sets the default configuration values used when calling
`pprint`, `cpprint`, or `pformat`, if those values weren't
explicitly provided. Only overrides the values provided in
the keyword arguments.
"""
global _default_config
if style is not _UNSET_SENTINEL:
set_default_style(style)
new_defaults = {**_default_config}
if max_seq_len is not _UNSET_SENTINEL:
new_defaults['max_seq_len'] = max_seq_len
if width is not _UNSET_SENTINEL:
new_defaults['width'] = width
if ribbon_width is not _UNSET_SENTINEL:
new_defaults['ribbon_width'] = ribbon_width
if depth is not _UNSET_SENTINEL:
new_defaults['depth'] = depth
if sort_dict_keys is not _UNSET_SENTINEL:
new_defaults['sort_dict_keys'] = sort_dict_keys
_default_config = new_defaults
return new_defaults
| (*, style=UNSET, max_seq_len=UNSET, width=UNSET, ribbon_width=UNSET, depth=UNSET, sort_dict_keys=UNSET) |
20,796 | prettyprinter.color | set_default_style | Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'``
| def set_default_style(style):
"""Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'``
"""
global default_style
if style == 'dark':
style = default_dark_style
elif style == 'light':
style = default_light_style
if not issubclass(style, Style):
raise TypeError(
"style must be a subclass of pygments.styles.Style or "
"one of 'dark', 'light'. Got {}".format(repr(style))
)
default_style = style
| (style) |
20,799 | prettyprinter.prettyprinter | trailing_comment | Annotates a value with a comment text, so that
the comment will be rendered "trailing", e.g. in place
of the last element in a list, set or tuple, or after
the last argument in a function.
This will force the rendering of ``value`` to be broken
to multiple lines as Python does not have inline comments.
>>> trailing_comment(['value'], '...and more')
[
'value',
# ...and more
]
| def trailing_comment(value, comment_text):
"""Annotates a value with a comment text, so that
the comment will be rendered "trailing", e.g. in place
of the last element in a list, set or tuple, or after
the last argument in a function.
This will force the rendering of ``value`` to be broken
to multiple lines as Python does not have inline comments.
>>> trailing_comment(['value'], '...and more')
[
'value',
# ...and more
]
"""
return _TrailingCommentedValue(value, comment_text)
| (value, comment_text) |
20,804 | pytest_level | pytest_addoption | null | def pytest_addoption(parser):
parser.addoption('--level', type=int)
| (parser) |
20,805 | pytest_level | pytest_collection_modifyitems | null | def pytest_collection_modifyitems(session, config, items):
selected_level = config.getoption('--level')
if selected_level == None:
return
deselected_items = set()
for item in items:
for marker in item.iter_markers('level'):
[marker_level] = marker.args
if marker_level > selected_level:
deselected_items.add(item)
selected_items = [item for item in items if item not in deselected_items]
items[:] = selected_items
config.hook.pytest_deselected(items=list(deselected_items))
| (session, config, items) |
20,806 | pytest_level | pytest_configure | null | def pytest_configure(config):
config.addinivalue_line(
"markers",
"level(lvl): Don't run the test if `lvl` is higher than current --level."
)
| (config) |
20,807 | precession.precession | affine |
Perform an affine trasformation to scale a vector given upper and lower limits: rescaled = ( vec - low ) / (up - low). If these are outside the domain of the vector, the result will be in [0,1].
Parameters
----------
vec: array
Vector in Cartesian coomponents.
low: float
Lower limit.
up: float
Upper limit.
Returns
-------
rescaled: float, optional
Rescaled vector.
Examples
--------
``rescaled = precession.affine(vec,low,up)``
| def affine(vec, low, up):
"""
Perform an affine trasformation to scale a vector given upper and lower limits: rescaled = ( vec - low ) / (up - low). If these are outside the domain of the vector, the result will be in [0,1].
Parameters
----------
vec: array
Vector in Cartesian coomponents.
low: float
Lower limit.
up: float
Upper limit.
Returns
-------
rescaled: float, optional
Rescaled vector.
Examples
--------
``rescaled = precession.affine(vec,low,up)``
"""
vec = np.atleast_1d(vec).astype(float)
up = np.atleast_1d(up).astype(float)
low = np.atleast_1d(low).astype(float)
rescaled = ( vec - low ) / (up - low)
return rescaled
| (vec, low, up) |
20,808 | precession.precession | angleresonances_endpoint |
Small-separation limit of the spin-orbit resonances.
Parameters
----------
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
chieff: float
Effective spin.
Returns
-------
deltaphiatmax: float
Value of the angle deltaphi at the resonance that maximizes kappa.
deltaphiatmin: float
Value of the angle deltaphi at the resonance that minimizes kappa.
theta1atmax: float
Value of the angle theta1 at the resonance that maximizes kappa.
theta1atmin: float
Value of the angle theta1 at the resonance that minimizes kappa.
theta2atmax: float
Value of the angle theta2 at the resonance that maximizes kappa.
theta2atmin: float
Value of the angle theta2 at the resonance that minimizes kappa.
Examples
--------
``theta1atmin,theta2atmin,deltaphiatmin,theta1atmax,theta2atmax,deltaphiatmax = precession.angleresonances_endpoint(q,chi1,chi2,chieff)``
| def angleresonances_endpoint(q, chi1, chi2, chieff):
"""
Small-separation limit of the spin-orbit resonances.
Parameters
----------
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
chieff: float
Effective spin.
Returns
-------
deltaphiatmax: float
Value of the angle deltaphi at the resonance that maximizes kappa.
deltaphiatmin: float
Value of the angle deltaphi at the resonance that minimizes kappa.
theta1atmax: float
Value of the angle theta1 at the resonance that maximizes kappa.
theta1atmin: float
Value of the angle theta1 at the resonance that minimizes kappa.
theta2atmax: float
Value of the angle theta2 at the resonance that maximizes kappa.
theta2atmin: float
Value of the angle theta2 at the resonance that minimizes kappa.
Examples
--------
``theta1atmin,theta2atmin,deltaphiatmin,theta1atmax,theta2atmax,deltaphiatmax = precession.angleresonances_endpoint(q,chi1,chi2,chieff)``
"""
q = np.atleast_1d(q).astype(float)
chi1 = np.atleast_1d(chi1).astype(float)
chi2 = np.atleast_1d(chi2).astype(float)
chieff = np.atleast_1d(chieff).astype(float)
chieff_uu = eval_chieff(0, 0, q, chi1, chi2)
chieff_ud = eval_chieff(0, -np.pi, q, chi1, chi2)
thetakappaplus = np.arccos(chieff / chieff_uu)
deltaphikappaplus = np.zeros_like(thetakappaplus)
condition = np.abs(chieff) <= np.abs(chieff_ud)
costheta1kappaminus_less = chieff / chieff_ud
costheta1kappaminus_gtr = (1+q) * (chieff**2+chieff_ud*chieff_uu) / (2*chi1*chieff)
costheta1kappaminus = np.where(condition, costheta1kappaminus_less, costheta1kappaminus_gtr)
theta1kappaminus = np.arccos(costheta1kappaminus)
costheta2kappaminus_less = -costheta1kappaminus_less
costheta2kappaminus_gtr = (1+q) * (chieff**2-chieff_ud*chieff_uu) / (2*q*chi2*chieff)
costheta2kappaminus = np.where(condition, costheta2kappaminus_less, costheta2kappaminus_gtr)
theta2kappaminus = np.arccos(costheta2kappaminus)
deltaphikappaminus = np.ones_like(condition) * np.pi
return np.stack([theta1kappaminus, theta2kappaminus, deltaphikappaminus, thetakappaplus, thetakappaplus, deltaphikappaplus])
| (q, chi1, chi2, chieff) |
20,809 | precession.precession | angles_to_Jframe |
Convert the angles (theta1,theta2,deltaphi) to angular momentum vectors (L,S1,S2) in the frame
aligned with the total angular momentum. In particular, we set Jx=Jy=Ly=0.
Parameters
----------
theta1: float
Angle between orbital angular momentum and primary spin.
theta2: float
Angle between orbital angular momentum and secondary spin.
deltaphi: float
Angle between the projections of the two spins onto the orbital plane.
r: float
Binary separation.
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
Returns
-------
Lvec: array
Cartesian vector of the orbital angular momentum.
S1vec: array
Cartesian vector of the primary spin.
S2vec: array
Cartesian vector of the secondary spin.
Examples
--------
``Lvec,S1vec,S2vec = precession.angles_to_Jframe(theta1,theta2,deltaphi,r,q,chi1,chi2)``
| def angles_to_Jframe(theta1, theta2, deltaphi, r, q, chi1, chi2):
"""
Convert the angles (theta1,theta2,deltaphi) to angular momentum vectors (L,S1,S2) in the frame
aligned with the total angular momentum. In particular, we set Jx=Jy=Ly=0.
Parameters
----------
theta1: float
Angle between orbital angular momentum and primary spin.
theta2: float
Angle between orbital angular momentum and secondary spin.
deltaphi: float
Angle between the projections of the two spins onto the orbital plane.
r: float
Binary separation.
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
Returns
-------
Lvec: array
Cartesian vector of the orbital angular momentum.
S1vec: array
Cartesian vector of the primary spin.
S2vec: array
Cartesian vector of the secondary spin.
Examples
--------
``Lvec,S1vec,S2vec = precession.angles_to_Jframe(theta1,theta2,deltaphi,r,q,chi1,chi2)``
"""
Lvec, S1vec, S2vec = angles_to_Lframe(theta1, theta2, deltaphi, r, q, chi1, chi2)
Lvec, S1vec, S2vec = vectors_to_Jframe(Lvec, S1vec, S2vec)
return np.stack([Lvec, S1vec, S2vec])
| (theta1, theta2, deltaphi, r, q, chi1, chi2) |
20,810 | precession.precession | angles_to_Lframe |
Convert the angles (theta1,theta2,deltaphi) to angular momentum vectors (L,S1,S2) in the frame
aligned with the orbital angular momentum. In particular, we set Lx=Ly=S1y=0.
Parameters
----------
theta1: float
Angle between orbital angular momentum and primary spin.
theta2: float
Angle between orbital angular momentum and secondary spin.
deltaphi: float
Angle between the projections of the two spins onto the orbital plane.
r: float
Binary separation.
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
Returns
-------
Lvec: array
Cartesian vector of the orbital angular momentum.
S1vec: array
Cartesian vector of the primary spin.
S2vec: array
Cartesian vector of the secondary spin.
Examples
--------
``Lvec,S1vec,S2vec = precession.angles_to_Lframe(theta1,theta2,deltaphi,r,q,chi1,chi2)``
| def angles_to_Lframe(theta1, theta2, deltaphi, r, q, chi1, chi2):
"""
Convert the angles (theta1,theta2,deltaphi) to angular momentum vectors (L,S1,S2) in the frame
aligned with the orbital angular momentum. In particular, we set Lx=Ly=S1y=0.
Parameters
----------
theta1: float
Angle between orbital angular momentum and primary spin.
theta2: float
Angle between orbital angular momentum and secondary spin.
deltaphi: float
Angle between the projections of the two spins onto the orbital plane.
r: float
Binary separation.
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
Returns
-------
Lvec: array
Cartesian vector of the orbital angular momentum.
S1vec: array
Cartesian vector of the primary spin.
S2vec: array
Cartesian vector of the secondary spin.
Examples
--------
``Lvec,S1vec,S2vec = precession.angles_to_Lframe(theta1,theta2,deltaphi,r,q,chi1,chi2)``
"""
L = eval_L(r, q)
S1 = eval_S1(q, chi1)
S2 = eval_S2(q, chi2)
Lx = np.zeros(L.shape)
Ly = np.zeros(L.shape)
Lz = L
Lvec = np.transpose([Lx, Ly, Lz])
S1x = S1 * np.sin(theta1)
S1y = np.zeros(S1.shape)
S1z = S1 * np.cos(theta1)
S1vec = np.transpose([S1x, S1y, S1z])
S2x = S2 * np.sin(theta2) * np.cos(deltaphi)
S2y = S2 * np.sin(theta2) * np.sin(deltaphi)
S2z = S2 * np.cos(theta2)
S2vec = np.transpose([S2x, S2y, S2z])
return np.stack([Lvec, S1vec, S2vec])
| (theta1, theta2, deltaphi, r, q, chi1, chi2) |
20,811 | precession.precession | angles_to_conserved |
Convert angles (theta1,theta2,deltaphi) into conserved quantities (deltachi,kappa,chieff).
Parameters
----------
theta1: float
Angle between orbital angular momentum and primary spin.
theta2: float
Angle between orbital angular momentum and secondary spin.
deltaphi: float
Angle between the projections of the two spins onto the orbital plane.
r: float
Binary separation.
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
full_output: boolean, optional (default: False)
Return additional outputs.
Returns
-------
chieff: float
Effective spin.
cyclesign: integer, optional
Sign (either +1 or -1) to cover the two halves of a precesion cycle.
deltachi: float
Weighted spin difference.
kappa: float
Asymptotic angular momentum.
Examples
--------
``deltachi,kappa,chieff = precession.angles_to_conserved(theta1,theta2,deltaphi,r,q,chi1,chi2)``
``deltachi,kappa,chieff,cyclesign = precession.angles_to_conserved(theta1,theta2,deltaphi,r,q,chi1,chi2,full_output=True)``
| def angles_to_conserved(theta1, theta2, deltaphi, r, q, chi1, chi2, full_output=False):
"""
Convert angles (theta1,theta2,deltaphi) into conserved quantities (deltachi,kappa,chieff).
Parameters
----------
theta1: float
Angle between orbital angular momentum and primary spin.
theta2: float
Angle between orbital angular momentum and secondary spin.
deltaphi: float
Angle between the projections of the two spins onto the orbital plane.
r: float
Binary separation.
q: float
Mass ratio: 0<=q<=1.
chi1: float
Dimensionless spin of the primary (heavier) black hole: 0<=chi1<=1.
chi2: float
Dimensionless spin of the secondary (lighter) black hole: 0<=chi2<=1.
full_output: boolean, optional (default: False)
Return additional outputs.
Returns
-------
chieff: float
Effective spin.
cyclesign: integer, optional
Sign (either +1 or -1) to cover the two halves of a precesion cycle.
deltachi: float
Weighted spin difference.
kappa: float
Asymptotic angular momentum.
Examples
--------
``deltachi,kappa,chieff = precession.angles_to_conserved(theta1,theta2,deltaphi,r,q,chi1,chi2)``
``deltachi,kappa,chieff,cyclesign = precession.angles_to_conserved(theta1,theta2,deltaphi,r,q,chi1,chi2,full_output=True)``
"""
deltachi = eval_deltachi(theta1, theta2, q, chi1, chi2)
kappa = eval_kappa(theta1=theta1, theta2=theta2, deltaphi=deltaphi, r=r, q=q, chi1=chi1, chi2=chi2)
chieff = eval_chieff(theta1, theta2, q, chi1, chi2)
if full_output:
cyclesign = np.where(r==np.inf,np.nan,eval_cyclesign(deltaphi=deltaphi))
return np.stack([deltachi, kappa, chieff, cyclesign])
else:
return np.stack([deltachi, kappa, chieff])
| (theta1, theta2, deltaphi, r, q, chi1, chi2, full_output=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.