Available Python Functions
- ArithmeticError(self, *args)
Base class for arithmetic errors.
- AssertionError(self, *args)
Assertion failed.
- AttributeError(self, *args, obj=None, name=None)
Attribute not found.
- Exception(self, *args)
Common base class for all non-exit exceptions.
- FloatingPointError(self, *args)
Floating point operation failed.
- ImportError(self, *args, name=None, path=None)
Import can't find module, or can't find name in module.
- IndexError(self, *args)
Sequence index out of range.
- KeyError(self, *args)
Mapping key not found.
- LookupError(self, *args)
Base class for lookup errors.
- MemoryError(self, *args)
Out of memory.
- ModuleNotFoundError(self, *args, name=None, path=None)
Module not found.
- NameError(self, *args, name=None)
Name not found globally.
- NotImplementedError(self, *args)
Method or function hasn't been implemented yet.
- OverflowError(self, *args)
Result too large to be represented.
- PermissionError(self, *args, **keywords)
Not enough permissions.
- RecursionError(self, *args)
Recursion limit exceeded.
- SyntaxError(self, *args)
Invalid syntax.
- TypeError(self, *args)
Inappropriate argument type.
- UnboundLocalError(self, *args, name=None)
Local name referenced but not bound to a value.
- UnicodeDecodeError(self, encoding, object, start, end, reason)
Unicode decoding error.
- UnicodeEncodeError(self, encoding, object, start, end, reason)
Unicode encoding error.
- UnicodeError(self, *args)
Unicode related error.
- UnicodeTranslateError(self, object, start, end, reason)
Unicode translation error.
- ValueError(self, *args)
Inappropriate argument value (of correct type).
- ZeroDivisionError(self, *args)
Second argument to a division or modulo operation was zero.
- abs(val)
abs(number) -> number
Return the absolute value of the argument.
- all(seq)
all(iterable) -> bool
Return True if bool(x) is True for all values x in the iterable.
- any(seq)
any(iterable) -> bool
Return True if bool(x) is True for any x in the iterable.
- base64.b64decode(s, altchars=None, validate=False)
Decode the Base64 encoded bytes-like object or ASCII string s.
Optional altchars must be a bytes-like object or ASCII string of length 2
which specifies the alternative alphabet used instead of the '+' and '/'
characters.
The result is returned as a bytes object. A binascii.Error is raised if
s is incorrectly padded.
If validate is False (the default), characters that are neither in the
normal base-64 alphabet nor the alternative alphabet are discarded prior
to the padding check. If validate is True, these non-alphabet characters
in the input result in a binascii.Error.
- base64.b64encode(s, altchars=None)
Encode the bytes-like object s using Base64 and return a bytes object.
Optional altchars should be a byte string of length 2 which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
- base64.decodebytes(s)
Decode a bytestring of base-64 data into a bytes object.
- base64.encodebytes(s)
Encode a bytestring into a bytes object containing multiple lines
of base-64 data.
- base64.urlsafe_b64decode(s)
Decode bytes using the URL- and filesystem-safe Base64 alphabet.
Argument s is a bytes-like object or ASCII string to decode. The result
is returned as a bytes object. A binascii.Error is raised if the input
is incorrectly padded. Characters that are not in the URL-safe base-64
alphabet, and are not a plus '+' or slash '/', are discarded prior to the
padding check.
The alphabet uses '-' instead of '+' and '_' instead of '/'.
- base64.urlsafe_b64encode(s)
Encode bytes using the URL- and filesystem-safe Base64 alphabet.
Argument s is a bytes-like object to encode. The result is returned as a
bytes object. The alphabet uses '-' instead of '+' and '_' instead of
'/'.
- bin(x)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
- bool(obj, *args, **keywords)
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
- bytearray(self, source=<no value>, encoding=<no value>, errors=<no value>)
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray
bytearray(memory_view) -> bytearray
Construct an mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a bytearray object
- any object implementing the buffer API.
bytearray(int) -> bytearray.
Construct a zero-initialized bytearray of the given length.
- bytes(obj, *args, **keywords)
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
- callable(object)
Check whether the object appears to be callable (i.e., some kind of
function). Note that classes are callable.
- chr(code)
Return a Unicode string of one character with the given ordinal.
- complex(obj, *args, **keywords)
complex(real[, imag]) -> complex number
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.
- datetime.date(year, month=None, day=None)
Concrete date type.
Constructors:
__new__()
fromtimestamp()
today()
fromordinal()
Operators:
__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
__add__, __radd__, __sub__ (add/radd only with timedelta arg)
Methods:
timetuple()
toordinal()
weekday()
isoweekday(), isocalendar(), isoformat()
ctime()
strftime()
Properties (readonly):
year, month, day
- datetime.datetime( year, month=None, day=None, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0, )
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints.
- datetime.datetime.date(self)
Return the date part.
- datetime.datetime.isoformat(self, sep='T', timespec='auto')
Return the time formatted according to ISO.
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
By default, the fractional part is omitted if self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
The optional argument timespec specifies the number of additional
terms of the time to include. Valid options are 'auto', 'hours',
'minutes', 'seconds', 'milliseconds' and 'microseconds'.
- datetime.datetime.now(tz=None)
Construct a datetime from time.time() and optional time zone info.
- datetime.datetime.time(self)
Return the time part, with tzinfo None.
- datetime.datetime.timestamp(self)
Return POSIX timestamp as float
- datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Time with time zone.
Constructors:
__new__()
Operators:
__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
Methods:
strftime()
isoformat()
utcoffset()
tzname()
dst()
Properties (readonly):
hour, minute, second, microsecond, tzinfo, fold
- datetime.timedelta( days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0, )
Represent the difference between two datetime objects.
Supported operators:
- add, subtract timedelta
- unary plus, minus, abs
- compare to timedelta
- multiply, divide by int
In addition, datetime supports subtraction of two datetime objects
returning a timedelta, and addition or subtraction of a datetime
and a timedelta giving a datetime.
Representation: (days, seconds, microseconds). Why? Because I
felt like it.
- datetime.timezone(offset, name=<object object at 0x234567>)
Abstract base class for time zone info classes.
Subclasses must override the name(), utcoffset() and dst() methods.
- datetime.tzinfo(*args, **kwds)
Abstract base class for time zone info classes.
Subclasses must override the name(), utcoffset() and dst() methods.
- decimal.Decimal(value='0', context=None)
Floating point class for decimal arithmetic.
- dict(self, *args, **keywords)
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
- dict.clear(self)
D.clear() -> None. Remove all items from D.
- dict.copy(self)
D.copy() -> a shallow copy of D
- dict.fromkeys(iterable, value=<no value>)
<no docstring>
- dict.get(self, key, default=None)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
- dict.items(self)
D.items() -> a set-like object providing a view on D's items
- dict.keys(self)
D.keys() -> a set-like object providing a view on D's keys
- dict.pop(self, key, default=<no value>)
D.pop(k[,d]) -> v, remove specified key and return the
corresponding value
If key is not found, d is returned if given,
otherwise KeyError is raised
- dict.popitem(self)
D.popitem() -> (k, v), remove and return some (key, value) pair as
a
2-tuple; but raise KeyError if D is empty
- dict.setdefault(self, key, default=None)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
- dict.update(self, *args, **keywords)
D.update(E, **F) -> None. Update D from E and F: for k in E: D[k]
= E[k]
(if E has keys else: for (k, v) in E: D[k] = v) then: for k in
F: D[k] = F[k]
- dict.values(self)
D.values() -> an object providing a view on D's values
- divmod(x, y)
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
- dys._chain(method, **params)
The main way to interact with the chain from a script.
:param method: the command to call on the chain, see TxBuilder for a list of possible commands
`**kwargs` will depend on the command being called
:returns: the response of the command or error
- dys.get_block_info() -> dict
Returns a dictionary of the current block info
- dys.get_caller() -> str
Returns the address of the caller of this script.
- dys.get_coins_sent()
Returns the coins sent to this function.
This is not the gas or gas fees.
- dys.get_cumulative_size()
The cumulative size of memory used for each node called in this query or script
- dys.get_gas_consumed()
The total amount of gas consumed so far.
- dys.get_gas_limit()
The maximum amount of gas that can be used in this query or transaction
- dys.get_nodes_called()
The number of Python AST nodes evaluated in this query or transaction
- dys.get_script_address() -> str
Returns the address of this current script.
- dys.rpc(method, **params)
Depricated
see: dyson._chain
- enumerate(obj, *args, **keywords)
<no docstring>
- filter(obj, *args, **keywords)
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
- frozenset(obj, *args, **keywords)
frozenset(iterable) --> frozenset object
Build an immutable unordered collection.
- hashlib.sha1(string=b'', usedforsecurity=True)
<no docstring>
- hashlib.sha256(string=b'', usedforsecurity=True)
<no docstring>
- hex(x)
Return the hexadecimal representation of an integer.
>>> hex(12648430)
'0xc0ffee'
- html.escape(s, quote=True)
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
- html.unescape(s)
Convert all named and numeric character references (e.g. >, >,
&x3e;) in the string s to the corresponding unicode characters.
This function uses the rules defined by the HTML 5 standard
for both valid and invalid character references, and the list of
HTML 5 named character references defined in html.entities.html5.
- int(obj, *args, **keywords)
int([x]) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
- io.BytesIO(self, initial_bytes=<no value>)
Base class for buffered IO objects.
The main difference with RawIOBase is that the read() method
supports omitting the size argument, and does not have a default
implementation that defers to readinto().
In addition, read(), readinto() and write() may raise
BlockingIOError if the underlying raw stream is in non-blocking
mode and not ready; unlike their raw counterparts, they will never
return None.
A typical implementation should not inherit from a RawIOBase
implementation, but wrap one.
- isinstance(obj, klass_or_tuple)
Check whether an object is an instance of a class (or of a subclass
thereof). When using a tuple as the second argument, check whether 'obj'
is an instance of any of the classes listed in the tuple.
- issubclass(cls, klass_or_tuple)
Check whether a class 'cls' is a subclass (i.e., a derived class) of
another class. When using a tuple as the second argument, check whether
'cls' is a subclass of any of the classes listed in the tuple.
- iter(collection_or_callable, sentinel=<no value>)
iter(collection) -> iterator over the elements of the collection.
iter(callable, sentinel) -> iterator calling callable() until it returns
the sentinel.
- len(obj)
len(object) -> integer
Return the number of items of a sequence or mapping.
- list(self, *args, **keywords)
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
- list.append(self, item)
L.append(object) -> None -- append object to end
- list.clear(self)
L.clear() -> None -- remove all items from L
- list.copy(self)
L.copy() -> list -- a shallow copy of L
- list.count(self, value)
L.count(value) -> integer -- return number of occurrences of value
- list.extend(self, iterable)
L.extend(iterable) -- extend list by appending elements from the iterable
- list.index(self, value, start=0, stop=9223372036854775807)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
- list.insert(self, index, value)
L.insert(index, object) -- insert object before index
- list.pop(self, index=-1)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
- list.remove(self, value)
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
- list.reverse(self)
L.reverse() -- reverse *IN PLACE*
- list.sort(self, key=<no value>, reverse=<no value>)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
- map(obj, *args, **keywords)
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
- max(*args, **keywords)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
- mimetypes.guess_type(url, strict=True)
Guess the type of a file based on its URL.
Return value is a tuple (type, encoding) where type is None if the
type can't be guessed (no or unknown suffix) or a string of the
form type/subtype, usable for a MIME Content-type header; and
encoding is None for no encoding or the name of the program used
to encode (e.g. compress or gzip). The mappings are table
driven. Encoding suffixes are case sensitive; type suffixes are
first tried case sensitive, then case insensitive.
The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
to ".tar.gz". (This is table-driven too, using the dictionary
suffix_map).
Optional `strict' argument when false adds a bunch of commonly found, but
non-standard types.
- min(*args, **keywords)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
- oct(x)
Return the octal representation of an integer.
>>> oct(342391)
'0o1234567'
- ord(val)
Return the integer ordinal of a character.
- pathlib.PurePath(*args)
Base class for manipulating paths without I/O.
PurePath represents a filesystem path and offers operations which
don't imply any actual filesystem I/O. Depending on your system,
instantiating a PurePath will return either a PurePosixPath or a
PureWindowsPath object. You can also instantiate either of these classes
directly, regardless of your system.
- pow(base, exp, mod=None)
With two arguments, equivalent to ``base**exp''.
With three arguments, equivalent to ``(base**exp) % mod''.
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
- print(*args, sep=' ', end='\n', file=None, flush=False)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
- random.Random.betavariate(self, alpha, beta)
Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
- random.Random.choice(self, seq)
Choose a random element from a non-empty sequence.
- random.Random.choices(self, population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
- random.Random.expovariate(self, lambd)
Exponential distribution.
lambd is 1.0 divided by the desired mean. It should be
nonzero. (The parameter would be called "lambda", but that is
a reserved word in Python.) Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.
- random.Random.gauss(self, mu, sigma)
Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
- random.Random.paretovariate(self, alpha)
Pareto distribution. alpha is the shape parameter.
- random.Random.sample(self, population, k, *, counts=None)
Chooses k unique random elements from a population sequence or set.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
Repeated elements can be specified one at a time or with the optional
counts parameter. For example:
sample(['red', 'blue'], counts=[4, 2], k=5)
is equivalent to:
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
To choose a sample from a range of integers, use range() for the
population argument. This is especially fast and space efficient
for sampling from a large population:
sample(range(10000000), 60)
- random.Random.seed(self, a=None, version=2)
Initialize internal state from a seed.
The only supported seed types are None, int, float,
str, bytes, and bytearray.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If *a* is an int, all bits are used.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
- random.Random.shuffle(self, x, random=None)
Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.
- random.Random.triangular(self, low=0.0, high=1.0, mode=None)
Triangular distribution.
Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution
- random.Random.uniform(self, a, b)
Get a random number in the range [a, b) or [a, b] depending on rounding.
- range(obj, *args, **keywords)
<no docstring>
- re2.BackreferencesException(self, *args)
Search pattern contains backreferences.
- re2.CharClassProblemException(self, *args)
Search pattern contains unsupported character class.
- re2.compile
<no docstring>
- re2.contains
Scan through string looking for a match to the pattern, returning
True or False.
- re2.count
Return number of non-overlapping matches in the string.
Empty matches are included in the count.
- re2.escape
Escape all non-alphanumeric characters in pattern.
- re2.findall
Return a list of all non-overlapping matches in the string.
Each match is represented as a string or a tuple (when there are two ore
more groups). Empty matches are included in the result.
- re2.finditer
Yield all non-overlapping matches in the string.
For each match, the iterator returns a ``Match`` object.
Empty matches are included in the result.
- re2.fullmatch
Try to apply the pattern to the entire string, returning
a ``Match`` object, or ``None`` if no match was found.
- re2.match
Try to apply the pattern at the start of the string, returning
a ``Match`` object, or ``None`` if no match was found.
- re2.search
Scan through string looking for a match to the pattern, returning
a ``Match`` object or none if no match was found.
- re2.split
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings.
- re2.sub
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement ``repl``. ``repl`` can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the ``Match`` object and must return
a replacement string to be used.
- re2.subn
Return a 2-tuple containing ``(new_string, number)``.
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement ``repl``. ``number`` is the number of
substitutions that were made. ``repl`` can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the ``Match`` object and must
return a replacement string to be used.
- reversed(obj, *args, **keywords)
<no docstring>
- round(number, ndigits=<no value>)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument or if ndigits=None,
otherwise the same type as the number. ndigits may be negative.
- set(self, *args, **keywords)
set(iterable) --> set object
Build an unordered collection.
- simplejson.dumps( obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False, **kw, )
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If *ensure_ascii* is false (default: ``True``), then the output may
contain non-ASCII characters, so long as they do not need to be escaped
by JSON. When it is true, all non-ASCII characters are escaped.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a string, then JSON array elements and object members
will be pretty-printed with a newline followed by that string repeated
for each level of nesting. ``None`` (the default) selects the most compact
representation without any newlines. For backwards compatibility with
versions of simplejson earlier than 2.1.0, an integer is also accepted
and is converted to a string with that many spaces.
If specified, ``separators`` should be an
``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``
if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most
compact JSON representation, you should specify ``(',', ':')`` to eliminate
whitespace.
``encoding`` is the character encoding for bytes instances, default is
UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *use_decimal* is true (default: ``True``) then decimal.Decimal
will be natively serialized to JSON with full precision.
If *namedtuple_as_object* is true (default: ``True``),
:class:`tuple` subclasses with ``_asdict()`` methods will be encoded
as JSON objects.
If *tuple_as_array* is true (default: ``True``),
:class:`tuple` (and subclasses) will be encoded as JSON arrays.
If *iterable_as_array* is true (default: ``False``),
any object not in the above table that implements ``__iter__()``
will be encoded as a JSON array.
If *bigint_as_string* is true (not the default), ints 2**53 and higher
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise.
If *int_as_string_bitcount* is a positive number (n), then int of size
greater than or equal to 2**n or lower than or equal to -2**n will be
encoded as strings.
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precedence over
*sort_keys*.
If *sort_keys* is true (default: ``False``), the output of dictionaries
will be sorted by item.
If *for_json* is true (default: ``False``), objects with a ``for_json()``
method will use the return value of that method for encoding as JSON
instead of the object.
If *ignore_nan* is true (default: ``False``), then out of range
:class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as
``null`` in compliance with the ECMA-262 specification. If true, this will
override *allow_nan*.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing
whenever possible.
- simplejson.errors.JSONDecodeError(msg, doc, pos, end=None)
Subclass of ValueError with the following additional properties:
msg: The unformatted error message
doc: The JSON document being parsed
pos: The start index of doc where parsing failed
end: The end index of doc where parsing failed (may be None)
lineno: The line corresponding to pos
colno: The column corresponding to pos
endlineno: The line corresponding to end (may be None)
endcolno: The column corresponding to end (may be None)
- simplejson.loads( s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw, )
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
*encoding* determines the encoding used to interpret any
:class:`bytes` objects decoded by this instance (``'utf-8'`` by
default). It has no effect when decoding :class:`unicode` objects.
*object_hook*, if specified, will be called with the result of every
JSON object decoded and its return value will be used in place of the
given :class:`dict`. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
*object_pairs_hook* is an optional function that will be called with
the result of any object literal decode with an ordered list of pairs.
The return value of *object_pairs_hook* will be used instead of the
:class:`dict`. This feature can be used to implement custom decoders
that rely on the order that the key and value pairs are decoded (for
example, :func:`collections.OrderedDict` will remember the order of
insertion). If *object_hook* is also defined, the *object_pairs_hook*
takes priority.
*parse_float*, if specified, will be called with the string of every
JSON float to be decoded. By default, this is equivalent to
``float(num_str)``. This can be used to use another datatype or parser
for JSON floats (e.g. :class:`decimal.Decimal`).
*parse_int*, if specified, will be called with the string of every
JSON int to be decoded. By default, this is equivalent to
``int(num_str)``. This can be used to use another datatype or parser
for JSON integers (e.g. :class:`float`).
*parse_constant*, if specified, will be called with one of the
following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This
can be used to raise an exception if invalid JSON numbers are
encountered.
If *use_decimal* is true (default: ``False``) then it implies
parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead
of subclassing whenever possible.
- slice(obj, *args, **keywords)
slice([start,] stop[, step])
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
- sorted(iterable, /, *, key=None, reverse=False)
sorted(iterable, key=None, reverse=False) --> new sorted list
- str(obj, *args, **keywords)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
- str.capitalize(self)
S.capitalize() -> unicode
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
- str.casefold(self)
S.casefold() -> str
Return a version of S suitable for caseless comparisons.
- str.count(self, sub, start=<no value>, end=<no value>)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
Unicode string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
- str.encode(self, encoding=<no value>, errors=<no value>)
S.encode(encoding=None, errors='strict') -> string or unicode
Encode S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
- str.endswith(self, suffix, start=<no value>, end=<no value>)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
- str.find(self, sub, start=<no value>, end=<no value>)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- str.index(self, sub, start=<no value>, end=<no value>)
S.index(sub[, start[, end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
- str.isalnum(self)
S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
- str.isalpha(self)
S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
- str.isascii(self)
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F.
Empty string is ASCII too.
- str.isdecimal(self)
S.isdecimal() -> bool
Return True if there are only decimal characters in S,
False otherwise.
- str.isdigit(self)
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
- str.isidentifier(self)
S.isidentifier() -> bool
Return True if S is a valid identifier according to the language
definition.
- str.islower(self)
S.islower() -> bool
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
- str.isnumeric(self)
S.isnumeric() -> bool
Return True if there are only numeric characters in S,
False otherwise.
- str.isprintable(self)
S.isprintable() -> bool
Return True if all characters in S are considered printable in
repr() or S is empty, False otherwise.
- str.isspace(self)
S.isspace() -> bool
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
- str.istitle(self)
S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
- str.isupper(self)
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
- str.join(self, iterable)
S.join(iterable) -> unicode
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
- str.lower(self)
S.lower() -> unicode
Return a copy of the string S converted to lowercase.
- str.lstrip(self, chars=<no value>)
S.lstrip([chars]) -> unicode
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is a str, it will be converted to unicode before stripping
- str.partition(self, sub)
S.partition(sep) -> (head, sep, tail)
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
- str.removeprefix(self, prefix)
<no docstring>
- str.removesuffix(self, suffix)
<no docstring>
- str.rfind(self, sub, start=<no value>, end=<no value>)
S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- str.rindex(self, sub, start=<no value>, end=<no value>)
S.rindex(sub[, start[, end]]) -> int
Like S.rfind() but raise ValueError when the substring is not found.
- str.rpartition(self, sub)
S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If
the separator is not found, return two empty strings and S.
- str.rsplit(self, sep=<no value>, maxsplit=<no value>)
S.rsplit(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
- str.rstrip(self, chars=<no value>)
S.rstrip([chars]) -> unicode
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is a str, it will be converted to unicode before stripping
- str.split(self, sep=<no value>, maxsplit=<no value>)
S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
- str.splitlines(self, keepends=False)
S.splitlines(keepends=False) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
- str.startswith(self, prefix, start=<no value>, end=<no value>)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
- str.strip(self, chars=<no value>)
S.strip([chars]) -> unicode
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is a str, it will be converted to unicode before stripping
- str.swapcase(self)
S.swapcase() -> unicode
Return a copy of S with uppercase characters converted to lowercase
and vice versa.
- str.title(self)
S.title() -> unicode
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
- str.upper(self)
S.upper() -> unicode
Return a copy of S converted to uppercase.
- string.Template(template)
A string class for supporting $-substitutions.
- string.Template.substitute(self, mapping={}, /, **kws)
<no docstring>
- string.capwords(s, sep=None)
capwords(s [,sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a single space
and leading and trailing whitespace are removed, otherwise
sep is used to split and join the words.
- sum(sequence, start=0)
sum(sequence[, start]) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, returns start.
- tuple(obj, *args, **keywords)
tuple() -> an empty tuple
tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
- typing.Annotated(*args, **kwargs)
Add context specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to the
hypothetical runtime_check module that this type is an unsigned int.
Every other consumer of this type can ignore this metadata and treat
this type as int.
The first argument to Annotated must be a valid type.
Details:
- It's an error to call `Annotated` with less than two arguments.
- Nested Annotated are flattened::
Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
- Instantiating an annotated type is equivalent to instantiating the
underlying type::
Annotated[C, Ann1](5) == C(5)
- Annotated can be used as a generic type alias::
Optimized = Annotated[T, runtime.Optimize()]
Optimized[int] == Annotated[int, runtime.Optimize()]
OptimizedList = Annotated[List[T], runtime.Optimize()]
OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
- typing.Any(*args, **kwds)
Special type indicating an unconstrained type.
- Any is compatible with every type.
- Any assumed to have all methods.
- All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of
static type checkers. At runtime, Any should not be used with instance
or class checks.
- typing.Callable(*args, **kwargs)
Callable type; Callable[[int], str] is a function of (int) -> str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type. The argument list
must be a list of types or ellipsis; the return type must be a single type.
There is no syntax to indicate optional or keyword arguments,
such function types are rarely used as callback types.
- typing.Literal(*args, **kwds)
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals):
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
- typing.Optional(*args, **kwds)
Optional type.
Optional[X] is equivalent to Union[X, None].
- typing.Union(*args, **kwds)
Union type; Union[X, Y] means either X or Y.
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
- urllib.parse.parse_qs( qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&', )
Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError if there
are more than n fields read by parse_qsl().
separator: str. The symbol to use for separating the query arguments.
Defaults to &.
Returns a dictionary.
- urllib.parse.parse_qsl( qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&', )
Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError
if there are more than n fields read by parse_qsl().
separator: str. The symbol to use for separating the query arguments.
Defaults to &.
Returns a list, as G-d intended.
- urllib.parse.quote(string, safe='/', encoding=None, errors=None)
quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted. The
quote function offers a cautious (not minimal) way to quote a
string for most of these parts.
RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists
the following (un)reserved characters.
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
Each of the reserved characters is reserved in some component of a URL,
but not necessarily in all of them.
The quote function %-escapes all characters that are neither in the
unreserved chars ("always safe") nor the additional chars set via the
safe arg.
The default for the safe arg is '/'. The character is reserved, but in
typical usage the quote function is being called on a path where the
existing slash characters are to be preserved.
Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
Now, "~" is included in the set of unreserved characters.
string and safe may be either str or bytes objects. encoding and errors
must not be specified if string is a bytes object.
The optional encoding and errors parameters specify how to deal with
non-ASCII characters, as accepted by the str.encode method.
By default, encoding='utf-8' (characters are encoded with UTF-8), and
errors='strict' (unsupported characters raise a UnicodeEncodeError).
- urllib.parse.quote_from_bytes(bs, safe='/')
Like quote(), but accepts a bytes object rather than a str, and does
not perform string-to-bytes encoding. It always returns an ASCII string.
quote_from_bytes(b'abc def?') -> 'abc%20def%3f'
- urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)
Like quote(), but also replace ' ' with '+', as required for quoting
HTML form values. Plus signs in the original string are escaped unless
they are included in safe. It also does not have safe default to '/'.
- urllib.parse.unquote(string, encoding='utf-8', errors='replace')
Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-encoded sequences are decoded with UTF-8, and invalid
sequences are replaced by a placeholder character.
unquote('abc%20def') -> 'abc def'.
- urllib.parse.unquote_plus(string, encoding='utf-8', errors='replace')
Like unquote(), but also replace plus signs by spaces, as required for
unquoting HTML form values.
unquote_plus('%7e/abc+def') -> '~/abc def'
- urllib.parse.unquote_to_bytes(string)
unquote_to_bytes('abc%20def') -> b'abc def'.
- urllib.parse.urldefrag(url)
Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
- urllib.parse.urljoin(base, url, allow_fragments=True)
Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter.
- urllib.parse.urlsplit(url, scheme='', allow_fragments=True)
Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
The result is a named 5-tuple with fields corresponding to the
above. It is either a SplitResult or SplitResultBytes object,
depending on the type of the url parameter.
The username, password, hostname, and port sub-components of netloc
can also be accessed as attributes of the returned object.
The scheme argument provides the default value of the scheme
component when no scheme is found in url.
If allow_fragments is False, no attempt is made to separate the
fragment component from the previous component, which can be either
path or query.
Note that % escapes are not expanded.
- urllib.parse.urlunsplit(components)
Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent).
- wsgiref.handlers.BaseHandler.start_response(self, status, headers, exc_info=None)
'start_response()' callable as specified by PEP 3333
- wsgiref.handlers.BaseHandler.write(self, data)
'write()' callable as specified by PEP 3333
- zip(obj, *args, **keywords)
Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.