Source code: Lib/json/__init__.py
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript 1 ).
json exposes an API familiar to users of the standard library marshal and pickle modules.
Encoding basic Python object hierarchies:
Compact encoding:
Pretty printing:
Decoding JSON:
Specializing JSON object decoding:
Extending JSONEncoder:
Using json.tool from the shell to validate and pretty-print:
See Command Line Interface for detailed documentation.
Note
JSON is a subset of YAML 1.2. The JSON produced by this module’s default settings (in particular, the default separators value) is also a subset of YAML 1.0 and 1.1. This module can thus also be used as a YAML serializer.
Note
This module’s encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered.
Prior to Python 3.7, dict was not guaranteed to be ordered, so inputs and outputs were typically scrambled unless collections.OrderedDict was specifically requested. Starting with Python 3.7, the regular dict became order preserving, so it is no longer necessary to specify collections.OrderedDict for JSON generation and parsing.
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.
If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
If check_circular is false (default: True), 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 (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is true, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used.
If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
Changed in version 3.2: Allow strings for indent in addition to integers.
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.
Changed in version 3.4: Use (',', ': ') as default if indent is not None.
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
Changed in version 3.6: All optional parameters are now keyword-only.
Note
Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.
Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().
Note
Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).
object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.
Changed in version 3.1: Added support for object_pairs_hook.
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. 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. 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.
Changed in version 3.1: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.
To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class.
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Changed in version 3.6: All optional parameters are now keyword-only.
Changed in version 3.6: fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32.
Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
The other arguments have the same meaning as in load().
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.
Changed in version 3.9: The keyword argument encoding has been removed.
Simple JSON decoder.
Performs the following translations in decoding by default:
JSON
Python
object
dict
array
list
string
str
number (int)
int
number (real)
float
true
True
false
False
null
None
It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec.
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 dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).
object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.
Changed in version 3.1: Added support for object_pairs_hook.
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. 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. 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 strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Changed in version 3.6: All parameters are now keyword-only.
Return the Python representation of s (a str instance containing a JSON document).
JSONDecodeError will be raised if the given JSON document is not valid.
Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.
This can be used to decode a JSON document from a string that may have extraneous data at the end.
Extensible JSON encoder for Python data structures.
Supports the following objects and types by default:
Python
JSON
dict
object
list, tuple
array
str
string
int, float, int- & float-derived Enums
number
True
true
False
false
None
null
Changed in version 3.4: Added support for int- and float-derived Enum classes.
To extend this to recognize other objects, subclass and implement a default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).
If skipkeys is false (the default), a TypeError will be raised when trying to encode keys that are not str, int, float or None. If skipkeys is true, such items are simply skipped.
If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
If check_circular is true (the default), then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.
If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
Changed in version 3.2: Allow strings for indent in addition to integers.
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.
Changed in version 3.4: Use (',', ': ') as default if indent is not None.
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
Changed in version 3.6: All parameters are now keyword-only.
Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).
For example, to support arbitrary iterators, you could implement default() like this:
Return a JSON string representation of a Python data structure, o. For example:
Encode the given object, o, and yield each string representation as available. For example:
Subclass of ValueError with the following additional attributes:
The unformatted error message.
The JSON document being parsed.
The start index of doc where parsing failed.
The line corresponding to pos.
The column corresponding to pos.
New in version 3.5.
The JSON format is specified by RFC 7159 and by ECMA-404. This section details this module’s level of compliance with the RFC. For simplicity, JSONEncoder and JSONDecoder subclasses, and parameters other than those explicitly mentioned, are not considered.
This module does not comply with the RFC in a strict fashion, implementing some extensions that are valid JavaScript but not valid JSON. In particular:
Since the RFC permits RFC-compliant parsers to accept input texts that are not RFC-compliant, this module’s deserializer is technically RFC-compliant under default settings.
The RFC requires that JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability.
As permitted, though not required, by the RFC, this module’s serializer sets ensure_ascii=True by default, thus escaping the output so that the resulting strings only contain ASCII characters.
Other than the ensure_ascii parameter, this module is defined strictly in terms of conversion between Python objects and Unicode strings, and thus does not otherwise directly address the issue of character encodings.
The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, and this module’s serializer does not add a BOM to its output. The RFC permits, but does not require, JSON deserializers to ignore an initial BOM in their input. This module’s deserializer raises a ValueError when an initial BOM is present.
The RFC does not explicitly forbid JSON strings which contain byte sequences that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16 surrogates), but it does note that they may cause interoperability problems. By default, this module accepts and outputs (when present in the original str) code points for such sequences.
The RFC does not permit the representation of infinite or NaN number values. Despite that, by default, this module accepts and outputs Infinity, -Infinity, and NaN as if they were valid JSON number literal values:
In the serializer, the allow_nan parameter can be used to alter this behavior. In the deserializer, the parse_constant parameter can be used to alter this behavior.
The RFC specifies that the names within a JSON object should be unique, but does not mandate how repeated names in JSON objects should be handled. By default, this module does not raise an exception; instead, it ignores all but the last name-value pair for a given name:
The object_pairs_hook parameter can be used to alter this behavior.
The old version of JSON specified by the obsolete RFC 4627 required that the top-level value of a JSON text must be either a JSON object or array (Python dict or list), and could not be a JSON null, boolean, number, or string value. RFC 7159 removed that restriction, and this module does not and has never implemented that restriction in either its serializer or its deserializer.
Regardless, for maximum interoperability, you may wish to voluntarily adhere to the restriction yourself.
Some JSON deserializer implementations may set limits on:
This module does not impose any such limits beyond those of the relevant Python datatypes themselves or the Python interpreter itself.
When serializing to JSON, beware any such limitations in applications that may consume your JSON. In particular, it is common for JSON numbers to be deserialized into IEEE 754 double precision numbers and thus subject to that representation’s range and precision limitations. This is especially relevant when serializing Python int values of extremely large magnitude, or when serializing instances of “exotic” numerical types such as decimal.Decimal.
Source code: Lib/json/tool.py
The json.tool module provides a simple command line interface to validate and pretty-print JSON objects.
If the optional infile and outfile arguments are not specified, sys.stdin and sys.stdout will be used respectively:
Changed in version 3.5: The output is now in the same order as the input. Use the --sort-keys option to sort the output of dictionaries alphabetically by key.
The JSON file to be validated or pretty-printed:
If infile is not specified, read from sys.stdin.
Write the output of the infile to the given outfile. Otherwise, write it to sys.stdout.
Sort the output of dictionaries alphabetically by key.
New in version 3.5.
Disable escaping of non-ascii characters, see json.dumps() for more information.
New in version 3.9.
Parse every input line as separate JSON object.
New in version 3.8.
Mutually exclusive options for whitespace control.
New in version 3.9.
Show the help message.
As noted in the errata for RFC 7159, JSON permits literal U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript (as of ECMAScript Edition 5.1) does not.


Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.
If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
If check_circular is false (default: True), 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 (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is true, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used.
If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
Changed in version 3.2: Allow strings for indent in addition to integers.
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.
Changed in version 3.4: Use (',', ': ') as default if indent is not None.
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
Changed in version 3.6: All optional parameters are now keyword-only.
Note
Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.


Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().
Note
Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.


Subclass of ValueError with the following additional attributes:
The unformatted error message.
The JSON document being parsed.
The start index of doc where parsing failed.
The line corresponding to pos.
The column corresponding to pos.
New in version 3.5.


The start index of doc where parsing failed.


Simple JSON decoder.
Performs the following translations in decoding by default:
JSON
Python
object
dict
array
list
string
str
number (int)
int
number (real)
float
true
True
false
False
null
None
It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec.
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 dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).
object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.
Changed in version 3.1: Added support for object_pairs_hook.
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. 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. 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 strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Changed in version 3.6: All parameters are now keyword-only.
Return the Python representation of s (a str instance containing a JSON document).
JSONDecodeError will be raised if the given JSON document is not valid.
Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.
This can be used to decode a JSON document from a string that may have extraneous data at the end.


Return the Python representation of s (a str instance containing a JSON document).
JSONDecodeError will be raised if the given JSON document is not valid.


Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.
This can be used to decode a JSON document from a string that may have extraneous data at the end.


Extensible JSON encoder for Python data structures.
Supports the following objects and types by default:
Python
JSON
dict
object
list, tuple
array
str
string
int, float, int- & float-derived Enums
number
True
true
False
false
None
null
Changed in version 3.4: Added support for int- and float-derived Enum classes.
To extend this to recognize other objects, subclass and implement a default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).
If skipkeys is false (the default), a TypeError will be raised when trying to encode keys that are not str, int, float or None. If skipkeys is true, such items are simply skipped.
If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
If check_circular is true (the default), then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.
If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
Changed in version 3.2: Allow strings for indent in addition to integers.
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.
Changed in version 3.4: Use (',', ': ') as default if indent is not None.
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
Changed in version 3.6: All parameters are now keyword-only.
Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).
For example, to support arbitrary iterators, you could implement default() like this:
Return a JSON string representation of a Python data structure, o. For example:
Encode the given object, o, and yield each string representation as available. For example:


Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).
For example, to support arbitrary iterators, you could implement default() like this:


Return a JSON string representation of a Python data structure, o. For example:


Encode the given object, o, and yield each string representation as available. For example:


Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).
object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.
Changed in version 3.1: Added support for object_pairs_hook.
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. 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. 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.
Changed in version 3.1: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.
To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class.
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Changed in version 3.6: All optional parameters are now keyword-only.
Changed in version 3.6: fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32.


Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
The other arguments have the same meaning as in load().
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.
Changed in version 3.9: The keyword argument encoding has been removed.


Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.


Raised when a mapping (dictionary) key is not found in the set of existing keys.


Source code: Lib/keyword.py
This module allows a Python program to determine if a string is a keyword.
Return True if s is a Python keyword.
Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.
Return True if s is a Python soft keyword.
New in version 3.9.
Sequence containing all the soft keywords defined for the interpreter. If any soft keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.
New in version 3.9.


Return True if s is a Python soft keyword.
New in version 3.9.


Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.


Sequence containing all the soft keywords defined for the interpreter. If any soft keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.
New in version 3.9.


Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
CPython implementation detail: len raises OverflowError on lengths larger than sys.maxsize, such as range(2 ** 100).


Object that when printed, prints the message “Type license() to see the full license text”, and when called, displays the full license text in a pager-like fashion (one screen at a time).


Source code: Lib/linecache.py
The linecache module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the traceback module to retrieve source lines for inclusion in the formatted traceback.
The tokenize.open() function is used to open files. This function uses tokenize.detect_encoding() to get the encoding of the file; in the absence of an encoding token, the file encoding defaults to UTF-8.
The linecache module defines the following functions:
Get line lineno from file named filename. This function will never raise an exception — it will return '' on errors (the terminating newline character will be included for lines that are found).
If a file named filename is not found, the function first checks for a PEP 302 __loader__ in module_globals. If there is such a loader and it defines a get_source method, then that determines the source lines (if get_source() returns None, then '' is returned). Finally, if filename is a relative filename, it is looked up relative to the entries in the module search path, sys.path.
Clear the cache. Use this function if you no longer need lines from files previously read using getline().
Check the cache for validity. Use this function if files in the cache may have changed on disk, and you require the updated version. If filename is omitted, it will check all the entries in the cache.
Capture enough detail about a non-file-based module to permit getting its lines later via getline() even if module_globals is None in the later call. This avoids doing I/O until a line is actually needed, without having to carry the module globals around indefinitely.
New in version 3.5.
Example:


Check the cache for validity. Use this function if files in the cache may have changed on disk, and you require the updated version. If filename is omitted, it will check all the entries in the cache.


Clear the cache. Use this function if you no longer need lines from files previously read using getline().


Get line lineno from file named filename. This function will never raise an exception — it will return '' on errors (the terminating newline character will be included for lines that are found).
If a file named filename is not found, the function first checks for a PEP 302 __loader__ in module_globals. If there is such a loader and it defines a get_source method, then that determines the source lines (if get_source() returns None, then '' is returned). Finally, if filename is a relative filename, it is looked up relative to the entries in the module search path, sys.path.


Capture enough detail about a non-file-based module to permit getting its lines later via getline() even if module_globals is None in the later call. This avoids doing I/O until a line is actually needed, without having to carry the module globals around indefinitely.
New in version 3.5.


Lists may be constructed in several ways:
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].
Many other operations also produce lists, including the sorted() built-in.
Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method:
This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):
key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.
The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance).
The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
For sorting examples and a brief sorting tutorial, see Sorting HOW TO.
CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.


Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.


This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):
key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.
The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance).
The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
For sorting examples and a brief sorting tutorial, see Sorting HOW TO.
CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.


Source code: Lib/locale.py
The locale module opens access to the POSIX locale database and functionality. The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.
The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.
The locale module defines the following exception and functions:
Exception raised when the locale passed to setlocale() is not recognized.
If locale is given and not None, setlocale() modifies the locale setting for the category. The available categories are listed in the data description below. locale may be a string, or an iterable of two strings (language code and encoding). If it’s an iterable, it’s converted to a locale name using the locale aliasing engine. An empty string specifies the user’s default settings. If the modification of the locale fails, the exception Error is raised. If successful, the new locale setting is returned.
If locale is omitted or None, the current setting for category is returned.
setlocale() is not thread-safe on most systems. Applications typically start with a call of
This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable). If the locale is not changed thereafter, using multithreading should not cause problems.
Returns the database of the local conventions as a dictionary. This dictionary has the following strings as keys:
Category
Key
Meaning
LC_NUMERIC
'decimal_point'
Decimal point character.
'grouping'
Sequence of numbers specifying which relative positions the 'thousands_sep' is expected. If the sequence is terminated with CHAR_MAX, no further grouping is performed. If the sequence terminates with a 0, the last group size is repeatedly used.
'thousands_sep'
Character used between groups.
LC_MONETARY
'int_curr_symbol'
International currency symbol.
'currency_symbol'
Local currency symbol.
'p_cs_precedes/n_cs_precedes'
Whether the currency symbol precedes the value (for positive resp. negative values).
'p_sep_by_space/n_sep_by_space'
Whether the currency symbol is separated from the value by a space (for positive resp. negative values).
'mon_decimal_point'
Decimal point used for monetary values.
'frac_digits'
Number of fractional digits used in local formatting of monetary values.
'int_frac_digits'
Number of fractional digits used in international formatting of monetary values.
'mon_thousands_sep'
Group separator used for monetary values.
'mon_grouping'
Equivalent to 'grouping', used for monetary values.
'positive_sign'
Symbol used to annotate a positive monetary value.
'negative_sign'
Symbol used to annotate a negative monetary value.
'p_sign_posn/n_sign_posn'
The position of the sign (for positive resp. negative values), see below.
All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale.
The possible values for 'p_sign_posn' and 'n_sign_posn' are given below.
Value
Explanation
0
Currency and value are surrounded by parentheses.
1
The sign should precede the value and currency symbol.
2
The sign should follow the value and currency symbol.
3
The sign should immediately precede the value.
4
The sign should immediately follow the value.
CHAR_MAX
Nothing is specified in this locale.
The function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. This temporary change affects other threads.
Changed in version 3.7: The function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.
Return some locale-specific information as a string. This function is not available on all systems, and the set of possible options might also vary across platforms. The possible argument values are numbers, for which symbolic constants are available in the locale module.
The nl_langinfo() function accepts one of the following keys. Most descriptions are taken from the corresponding description in the GNU C library.
Get a string with the name of the character encoding used in the selected locale.
Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.
Get a format string for time.strftime() to represent time in the am/pm format.
Get the name of the n-th day of the week.
Note
This follows the US convention of DAY_1 being Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.
Get the abbreviated name of the n-th day of the week.
Get the name of the n-th month.
Get the abbreviated name of the n-th month.
Get the radix character (decimal dot, decimal comma, etc.).
Get the separator character for thousands (groups of three digits).
Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.
Note
The expression is in the syntax suitable for the regex() function from the C library, which might differ from the syntax used in re.
Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.
Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.
Get a string that represents the era used in the current locale.
Most locales do not define this value. An example of a locale which does define this value is the Japanese one. In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.
Normally it should not be necessary to use this value directly. Specifying the E modifier in their format strings causes the time.strftime() function to use this information. The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.
Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.
Get a format string for time.strftime() to represent a date in a locale-specific era-based way.
Get a format string for time.strftime() to represent a time in a locale-specific era-based way.
Get a representation of up to 100 values used to represent the values 0 to 99.
Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding).
According to POSIX, a program which has not called setlocale(LC_ALL, '') runs using the portable 'C' locale. Calling setlocale(LC_ALL, '') lets it use the default locale as defined by the LANG variable. Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above.
To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name 'LANG'. The GNU gettext search path contains 'LC_ALL', 'LC_CTYPE', 'LANG' and 'LANGUAGE', in that order.
Except for the code 'C', the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.
Returns the current setting for the given locale category as sequence containing language code, encoding. category may be one of the LC_* values except LC_ALL. It defaults to LC_CTYPE.
Except for the code 'C', the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.
Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
On some systems, it is necessary to invoke setlocale() to obtain the user preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, do_setlocale should be set to False.
On Android or in the UTF-8 mode (-X utf8 option), always return 'UTF-8', the locale and the do_setlocale argument are ignored.
Changed in version 3.7: The function now always returns UTF-8 on Android or if the UTF-8 mode is enabled.
Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale(). If normalization fails, the original name is returned unchanged.
If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale().
Sets the locale for category to the default setting.
The default setting is determined by calling getdefaultlocale(). category defaults to LC_ALL.
Compares two strings according to the current LC_COLLATE setting. As any other compare function, returns a negative, or a positive value, or 0, depending on whether string1 collates before or after string2 or is equal to it.
Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) is equivalent to strcoll(s1, s2) < 0. This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.
Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is true, also takes the grouping into account.
If monetary is true, the conversion uses monetary thousands separator and grouping strings.
Processes formatting specifiers as in format % val, but takes the current locale settings into account.
Changed in version 3.7: The monetary keyword parameter was added.
Please note that this function works like format_string() but will only work for exactly one %char specifier. For example, '%f' and '%.0f' are both valid specifiers, but '%f KiB' is not.
For whole format strings, use format_string().
Deprecated since version 3.7: Use format_string() instead.
Formats a number val according to the current LC_MONETARY settings.
The returned string includes the currency symbol if symbol is true, which is the default. If grouping is true (which is not the default), grouping is done with the value. If international is true (which is not the default), the international currency symbol is used.
Note that this function will not work with the ‘C’ locale, so you have to set a locale via setlocale() first.
Formats a floating point number using the same format as the built-in function str(float), but takes the decimal point into account.
Converts a string into a normalized number string, following the LC_NUMERIC settings.
New in version 3.5.
Converts a string to a floating point number, following the LC_NUMERIC settings.
Converts a string to an integer, following the LC_NUMERIC conventions.
Locale category for the character type functions. Depending on the settings of this category, the functions of module string dealing with case change their behaviour.
Locale category for sorting strings. The functions strcoll() and strxfrm() of the locale module are affected.
Locale category for the formatting of time. The function time.strftime() follows these conventions.
Locale category for formatting of monetary values. The available options are available from the localeconv() function.
Locale category for message display. Python currently does not support application specific locale-aware messages. Messages displayed by the operating system, like those returned by os.strerror() might be affected by this category.
Locale category for formatting numbers. The functions format(), atoi(), atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected.
Combination of all locale settings. If this flag is used when the locale is changed, setting the locale for all categories is attempted. If that fails for any category, no category is changed at all. When the locale is retrieved using this flag, a string indicating the setting for all categories is returned. This string can be later used to restore the settings.
This is a symbolic constant used for different values returned by localeconv().
Example:
The C standard defines the locale as a program-wide property that may be relatively expensive to change. On top of that, some implementation are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly.
Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, '').
It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.
If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime()), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. Only as a last resort should you document that your module is not compatible with non-C locale settings.
The only way to perform numeric operations according to the locale is to use the special functions defined by this module: atof(), atoi(), format(), str().
There is no way to perform case conversions and character classifications according to the locale. For (Unicode) text strings these are done according to the character value only, while for byte strings, the conversions and classifications are done according to the ASCII value of the byte, and bytes whose high bit is set (i.e., non-ASCII bytes) are never converted or considered part of a character class such as letter or whitespace.
Extension modules should never call setlocale(), except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C).
When Python code uses the locale module to change the locale, this also affects the embedding application. If the embedding application doesn’t want this to happen, it should remove the _locale extension module (which does all the work) from the table of built-in modules in the config.c file, and make sure that the _locale module is not accessible as a shared library.
The locale module exposes the C library’s gettext interface on systems that provide this interface. It consists of the functions gettext(), dgettext(), dcgettext(), textdomain(), bindtextdomain(), and bind_textdomain_codeset(). These are similar to the same functions in the gettext module, but use the C library’s binary format for message catalogs, and the C library’s search algorithms for locating message catalogs.
Python applications should normally find no need to invoke these functions, and should use gettext instead. A known exception to this rule are applications that link with additional C libraries which internally invoke gettext() or dcgettext(). For these applications, it may be necessary to bind the text domain, so that the libraries can properly locate their message catalogs.


Get a representation of up to 100 values used to represent the values 0 to 99.


Converts a string to a floating point number, following the LC_NUMERIC settings.


Converts a string to an integer, following the LC_NUMERIC conventions.


This is a symbolic constant used for different values returned by localeconv().


Get a string with the name of the character encoding used in the selected locale.


Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.


Formats a number val according to the current LC_MONETARY settings.
The returned string includes the currency symbol if symbol is true, which is the default. If grouping is true (which is not the default), grouping is done with the value. If international is true (which is not the default), the international currency symbol is used.
Note that this function will not work with the ‘C’ locale, so you have to set a locale via setlocale() first.


Converts a string into a normalized number string, following the LC_NUMERIC settings.
New in version 3.5.


Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.


Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.


Get a string that represents the era used in the current locale.
Most locales do not define this value. An example of a locale which does define this value is the Japanese one. In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.
Normally it should not be necessary to use this value directly. Specifying the E modifier in their format strings causes the time.strftime() function to use this information. The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.


Get a format string for time.strftime() to represent a date in a locale-specific era-based way.


Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.


Get a format string for time.strftime() to represent a time in a locale-specific era-based way.


Exception raised when the locale passed to setlocale() is not recognized.


Please note that this function works like format_string() but will only work for exactly one %char specifier. For example, '%f' and '%.0f' are both valid specifiers, but '%f KiB' is not.
For whole format strings, use format_string().
Deprecated since version 3.7: Use format_string() instead.


Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is true, also takes the grouping into account.
If monetary is true, the conversion uses monetary thousands separator and grouping strings.
Processes formatting specifiers as in format % val, but takes the current locale settings into account.
Changed in version 3.7: The monetary keyword parameter was added.


Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding).
According to POSIX, a program which has not called setlocale(LC_ALL, '') runs using the portable 'C' locale. Calling setlocale(LC_ALL, '') lets it use the default locale as defined by the LANG variable. Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above.
To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name 'LANG'. The GNU gettext search path contains 'LC_ALL', 'LC_CTYPE', 'LANG' and 'LANGUAGE', in that order.
Except for the code 'C', the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.


Returns the current setting for the given locale category as sequence containing language code, encoding. category may be one of the LC_* values except LC_ALL. It defaults to LC_CTYPE.
Except for the code 'C', the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.


Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
On some systems, it is necessary to invoke setlocale() to obtain the user preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, do_setlocale should be set to False.
On Android or in the UTF-8 mode (-X utf8 option), always return 'UTF-8', the locale and the do_setlocale argument are ignored.
Changed in version 3.7: The function now always returns UTF-8 on Android or if the UTF-8 mode is enabled.


Combination of all locale settings. If this flag is used when the locale is changed, setting the locale for all categories is attempted. If that fails for any category, no category is changed at all. When the locale is retrieved using this flag, a string indicating the setting for all categories is returned. This string can be later used to restore the settings.


Locale category for sorting strings. The functions strcoll() and strxfrm() of the locale module are affected.


Locale category for the character type functions. Depending on the settings of this category, the functions of module string dealing with case change their behaviour.


Locale category for message display. Python currently does not support application specific locale-aware messages. Messages displayed by the operating system, like those returned by os.strerror() might be affected by this category.


Locale category for formatting of monetary values. The available options are available from the localeconv() function.


Locale category for formatting numbers. The functions format(), atoi(), atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected.


Locale category for the formatting of time. The function time.strftime() follows these conventions.


Returns the database of the local conventions as a dictionary. This dictionary has the following strings as keys:
Category
Key
Meaning
LC_NUMERIC
'decimal_point'
Decimal point character.
'grouping'
Sequence of numbers specifying which relative positions the 'thousands_sep' is expected. If the sequence is terminated with CHAR_MAX, no further grouping is performed. If the sequence terminates with a 0, the last group size is repeatedly used.
'thousands_sep'
Character used between groups.
LC_MONETARY
'int_curr_symbol'
International currency symbol.
'currency_symbol'
Local currency symbol.
'p_cs_precedes/n_cs_precedes'
Whether the currency symbol precedes the value (for positive resp. negative values).
'p_sep_by_space/n_sep_by_space'
Whether the currency symbol is separated from the value by a space (for positive resp. negative values).
'mon_decimal_point'
Decimal point used for monetary values.
'frac_digits'
Number of fractional digits used in local formatting of monetary values.
'int_frac_digits'
Number of fractional digits used in international formatting of monetary values.
'mon_thousands_sep'
Group separator used for monetary values.
'mon_grouping'
Equivalent to 'grouping', used for monetary values.
'positive_sign'
Symbol used to annotate a positive monetary value.
'negative_sign'
Symbol used to annotate a negative monetary value.
'p_sign_posn/n_sign_posn'
The position of the sign (for positive resp. negative values), see below.
All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale.
The possible values for 'p_sign_posn' and 'n_sign_posn' are given below.
Value
Explanation
0
Currency and value are surrounded by parentheses.
1
The sign should precede the value and currency symbol.
2
The sign should follow the value and currency symbol.
3
The sign should immediately precede the value.
4
The sign should immediately follow the value.
CHAR_MAX
Nothing is specified in this locale.
The function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. This temporary change affects other threads.
Changed in version 3.7: The function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.


Return some locale-specific information as a string. This function is not available on all systems, and the set of possible options might also vary across platforms. The possible argument values are numbers, for which symbolic constants are available in the locale module.
The nl_langinfo() function accepts one of the following keys. Most descriptions are taken from the corresponding description in the GNU C library.
Get a string with the name of the character encoding used in the selected locale.
Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.
Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.
Get a format string for time.strftime() to represent time in the am/pm format.
Get the name of the n-th day of the week.
Note
This follows the US convention of DAY_1 being Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.
Get the abbreviated name of the n-th day of the week.
Get the name of the n-th month.
Get the abbreviated name of the n-th month.
Get the radix character (decimal dot, decimal comma, etc.).
Get the separator character for thousands (groups of three digits).
Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.
Note
The expression is in the syntax suitable for the regex() function from the C library, which might differ from the syntax used in re.
Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.
Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.
Get a string that represents the era used in the current locale.
Most locales do not define this value. An example of a locale which does define this value is the Japanese one. In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.
Normally it should not be necessary to use this value directly. Specifying the E modifier in their format strings causes the time.strftime() function to use this information. The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.
Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.
Get a format string for time.strftime() to represent a date in a locale-specific era-based way.
Get a format string for time.strftime() to represent a time in a locale-specific era-based way.
Get a representation of up to 100 values used to represent the values 0 to 99.


Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.


Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale(). If normalization fails, the original name is returned unchanged.
If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale().


Get the radix character (decimal dot, decimal comma, etc.).


Sets the locale for category to the default setting.
The default setting is determined by calling getdefaultlocale(). category defaults to LC_ALL.


If locale is given and not None, setlocale() modifies the locale setting for the category. The available categories are listed in the data description below. locale may be a string, or an iterable of two strings (language code and encoding). If it’s an iterable, it’s converted to a locale name using the locale aliasing engine. An empty string specifies the user’s default settings. If the modification of the locale fails, the exception Error is raised. If successful, the new locale setting is returned.
If locale is omitted or None, the current setting for category is returned.
setlocale() is not thread-safe on most systems. Applications typically start with a call of
This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable). If the locale is not changed thereafter, using multithreading should not cause problems.


Formats a floating point number using the same format as the built-in function str(float), but takes the decimal point into account.


Compares two strings according to the current LC_COLLATE setting. As any other compare function, returns a negative, or a positive value, or 0, depending on whether string1 collates before or after string2 or is equal to it.


Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) is equivalent to strcoll(s1, s2) < 0. This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.


Get the separator character for thousands (groups of three digits).


Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.


Get a format string for time.strftime() to represent time in the am/pm format.


Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.
Note
The expression is in the syntax suitable for the regex() function from the C library, which might differ from the syntax used in re.


Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.