doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
Pattern.groupindex
A dictionary mapping any symbolic group names defined by (?P<id>) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern. | python.library.re#re.Pattern.groupindex |
Pattern.groups
The number of capturing groups in the pattern. | python.library.re#re.Pattern.groups |
Pattern.match(string[, pos[, endpos]])
If zero or more characters at the beginning of string match this regular expression, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match. The optional pos and endpos parameters have the same meaning as for the search() method. >>> pattern = re.compile("o")
>>> pattern.match("dog") # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog".
<re.Match object; span=(1, 2), match='o'>
If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()). | python.library.re#re.Pattern.match |
Pattern.pattern
The pattern string from which the pattern object was compiled. | python.library.re#re.Pattern.pattern |
Pattern.search(string[, pos[, endpos]])
Scan through string looking for the first location where this regular expression produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the '^' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start. The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos, no match will be found; otherwise, if rx is a compiled regular expression object, rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0). >>> pattern = re.compile("d")
>>> pattern.search("dog") # Match at index 0
<re.Match object; span=(0, 1), match='d'>
>>> pattern.search("dog", 1) # No match; search doesn't include the "d" | python.library.re#re.Pattern.search |
Pattern.split(string, maxsplit=0)
Identical to the split() function, using the compiled pattern. | python.library.re#re.Pattern.split |
Pattern.sub(repl, string, count=0)
Identical to the sub() function, using the compiled pattern. | python.library.re#re.Pattern.sub |
Pattern.subn(repl, string, count=0)
Identical to the subn() function, using the compiled pattern. | python.library.re#re.Pattern.subn |
re.purge()
Clear the regular expression cache. | python.library.re#re.purge |
re.S
re.DOTALL
Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s). | python.library.re#re.S |
re.search(pattern, string, flags=0)
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. | python.library.re#re.search |
re.split(pattern, string, maxsplit=0, flags=0)
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string: >>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
That way, separator components are always found at the same relative indices within the result list. Empty matches for the pattern split the string only when not adjacent to a previous empty match. >>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
Changed in version 3.1: Added the optional flags argument. Changed in version 3.7: Added support of splitting on a pattern that could match an empty string. | python.library.re#re.split |
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
... r'static PyObject*\npy_\1(void)\n{',
... 'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'
The pattern may be a string or a pattern object. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous empty match, so sub('x*', '-', 'abxd') returns '-a-b--d-'. In string-type repl arguments, in addition to the character escapes and backreferences described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE. Changed in version 3.1: Added the optional flags argument. Changed in version 3.5: Unmatched groups are replaced with an empty string. Changed in version 3.6: Unknown escapes in pattern consisting of '\' and an ASCII letter now are errors. Changed in version 3.7: Unknown escapes in repl consisting of '\' and an ASCII letter now are errors. Changed in version 3.7: Empty matches for the pattern are replaced when adjacent to a previous non-empty match. | python.library.re#re.sub |
re.subn(pattern, repl, string, count=0, flags=0)
Perform the same operation as sub(), but return a tuple (new_string,
number_of_subs_made). Changed in version 3.1: Added the optional flags argument. Changed in version 3.5: Unmatched groups are replaced with an empty string. | python.library.re#re.subn |
re.X
re.VERBOSE
This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored. This means that the two following regular expression objects that match a decimal number are functionally equal: a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
Corresponds to the inline flag (?x). | python.library.re#re.VERBOSE |
re.X
re.VERBOSE
This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored. This means that the two following regular expression objects that match a decimal number are functionally equal: a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
Corresponds to the inline flag (?x). | python.library.re#re.X |
readline — GNU readline interface The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly, or via the rlcompleter module, which supports completion of Python identifiers at the interactive prompt. Settings made using this module affect the behaviour of both the interpreter’s interactive prompt and the prompts offered by the built-in input() function. Readline keybindings may be configured via an initialization file, typically .inputrc in your home directory. See Readline Init File in the GNU Readline manual for information about the format and allowable constructs of that file, and the capabilities of the Readline library in general. Note The underlying Readline library API may be implemented by the libedit library instead of GNU readline. On macOS the readline module detects which library is being used at run time. The configuration file for libedit is different from that of GNU readline. If you programmatically load configuration strings you can check for the text “libedit” in readline.__doc__ to differentiate between GNU readline and libedit. If you use editline/libedit readline emulation on macOS, the initialization file located in your home directory is named .editrc. For example, the following content in ~/.editrc will turn ON vi keybindings and TAB completion: python:bind -v
python:bind ^I rl_complete
Init file The following functions relate to the init file and user configuration:
readline.parse_and_bind(string)
Execute the init line provided in the string argument. This calls rl_parse_and_bind() in the underlying library.
readline.read_init_file([filename])
Execute a readline initialization file. The default filename is the last filename used. This calls rl_read_init_file() in the underlying library.
Line buffer The following functions operate on the line buffer:
readline.get_line_buffer()
Return the current contents of the line buffer (rl_line_buffer in the underlying library).
readline.insert_text(string)
Insert text into the line buffer at the cursor position. This calls rl_insert_text() in the underlying library, but ignores the return value.
readline.redisplay()
Change what’s displayed on the screen to reflect the current contents of the line buffer. This calls rl_redisplay() in the underlying library.
History file The following functions operate on a history file:
readline.read_history_file([filename])
Load a readline history file, and append it to the history list. The default filename is ~/.history. This calls read_history() in the underlying library.
readline.write_history_file([filename])
Save the history list to a readline history file, overwriting any existing file. The default filename is ~/.history. This calls write_history() in the underlying library.
readline.append_history_file(nelements[, filename])
Append the last nelements items of history to a file. The default filename is ~/.history. The file must already exist. This calls append_history() in the underlying library. This function only exists if Python was compiled for a version of the library that supports it. New in version 3.5.
readline.get_history_length()
readline.set_history_length(length)
Set or return the desired number of lines to save in the history file. The write_history_file() function uses this value to truncate the history file, by calling history_truncate_file() in the underlying library. Negative values imply unlimited history file size.
History list The following functions operate on a global history list:
readline.clear_history()
Clear the current history. This calls clear_history() in the underlying library. The Python function only exists if Python was compiled for a version of the library that supports it.
readline.get_current_history_length()
Return the number of items currently in the history. (This is different from get_history_length(), which returns the maximum number of lines that will be written to a history file.)
readline.get_history_item(index)
Return the current contents of history item at index. The item index is one-based. This calls history_get() in the underlying library.
readline.remove_history_item(pos)
Remove history item specified by its position from the history. The position is zero-based. This calls remove_history() in the underlying library.
readline.replace_history_item(pos, line)
Replace history item specified by its position with line. The position is zero-based. This calls replace_history_entry() in the underlying library.
readline.add_history(line)
Append line to the history buffer, as if it was the last line typed. This calls add_history() in the underlying library.
readline.set_auto_history(enabled)
Enable or disable automatic calls to add_history() when reading input via readline. The enabled argument should be a Boolean value that when true, enables auto history, and that when false, disables auto history. New in version 3.6. CPython implementation detail: Auto history is enabled by default, and changes to this do not persist across multiple sessions.
Startup hooks
readline.set_startup_hook([function])
Set or remove the function invoked by the rl_startup_hook callback of the underlying library. If function is specified, it will be used as the new hook function; if omitted or None, any function already installed is removed. The hook is called with no arguments just before readline prints the first prompt.
readline.set_pre_input_hook([function])
Set or remove the function invoked by the rl_pre_input_hook callback of the underlying library. If function is specified, it will be used as the new hook function; if omitted or None, any function already installed is removed. The hook is called with no arguments after the first prompt has been printed and just before readline starts reading input characters. This function only exists if Python was compiled for a version of the library that supports it.
Completion The following functions relate to implementing a custom word completion function. This is typically operated by the Tab key, and can suggest and automatically complete a word being typed. By default, Readline is set up to be used by rlcompleter to complete Python identifiers for the interactive interpreter. If the readline module is to be used with a custom completer, a different set of word delimiters should be set.
readline.set_completer([function])
Set or remove the completer function. If function is specified, it will be used as the new completer function; if omitted or None, any completer function already installed is removed. The completer function is called as function(text, state), for state in 0, 1, 2, …, until it returns a non-string value. It should return the next possible completion starting with text. The installed completer function is invoked by the entry_func callback passed to rl_completion_matches() in the underlying library. The text string comes from the first parameter to the rl_attempted_completion_function callback of the underlying library.
readline.get_completer()
Get the completer function, or None if no completer function has been set.
readline.get_completion_type()
Get the type of completion being attempted. This returns the rl_completion_type variable in the underlying library as an integer.
readline.get_begidx()
readline.get_endidx()
Get the beginning or ending index of the completion scope. These indexes are the start and end arguments passed to the rl_attempted_completion_function callback of the underlying library.
readline.set_completer_delims(string)
readline.get_completer_delims()
Set or get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the rl_completer_word_break_characters variable in the underlying library.
readline.set_completion_display_matches_hook([function])
Set or remove the completion display function. If function is specified, it will be used as the new completion display function; if omitted or None, any completion display function already installed is removed. This sets or clears the rl_completion_display_matches_hook callback in the underlying library. The completion display function is called as function(substitution, [matches], longest_match_length) once each time matches need to be displayed.
Example The following example demonstrates how to use the readline module’s history reading and writing functions to automatically load and save a history file named .python_history from the user’s home directory. The code below would normally be executed automatically during interactive sessions from the user’s PYTHONSTARTUP file. import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
readline.read_history_file(histfile)
# default history len is -1 (infinite), which may grow unruly
readline.set_history_length(1000)
except FileNotFoundError:
pass
atexit.register(readline.write_history_file, histfile)
This code is actually automatically run when Python is run in interactive mode (see Readline configuration). The following example achieves the same goal but supports concurrent interactive sessions, by only appending the new history. import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
readline.read_history_file(histfile)
h_len = readline.get_current_history_length()
except FileNotFoundError:
open(histfile, 'wb').close()
h_len = 0
def save(prev_h_len, histfile):
new_h_len = readline.get_current_history_length()
readline.set_history_length(1000)
readline.append_history_file(new_h_len - prev_h_len, histfile)
atexit.register(save, h_len, histfile)
The following example extends the code.InteractiveConsole class to support history save/restore. import atexit
import code
import os
import readline
class HistoryConsole(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>",
histfile=os.path.expanduser("~/.console-history")):
code.InteractiveConsole.__init__(self, locals, filename)
self.init_history(histfile)
def init_history(self, histfile):
readline.parse_and_bind("tab: complete")
if hasattr(readline, "read_history_file"):
try:
readline.read_history_file(histfile)
except FileNotFoundError:
pass
atexit.register(self.save_history, histfile)
def save_history(self, histfile):
readline.set_history_length(1000)
readline.write_history_file(histfile) | python.library.readline |
readline.add_history(line)
Append line to the history buffer, as if it was the last line typed. This calls add_history() in the underlying library. | python.library.readline#readline.add_history |
readline.append_history_file(nelements[, filename])
Append the last nelements items of history to a file. The default filename is ~/.history. The file must already exist. This calls append_history() in the underlying library. This function only exists if Python was compiled for a version of the library that supports it. New in version 3.5. | python.library.readline#readline.append_history_file |
readline.clear_history()
Clear the current history. This calls clear_history() in the underlying library. The Python function only exists if Python was compiled for a version of the library that supports it. | python.library.readline#readline.clear_history |
readline.get_begidx()
readline.get_endidx()
Get the beginning or ending index of the completion scope. These indexes are the start and end arguments passed to the rl_attempted_completion_function callback of the underlying library. | python.library.readline#readline.get_begidx |
readline.get_completer()
Get the completer function, or None if no completer function has been set. | python.library.readline#readline.get_completer |
readline.set_completer_delims(string)
readline.get_completer_delims()
Set or get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the rl_completer_word_break_characters variable in the underlying library. | python.library.readline#readline.get_completer_delims |
readline.get_completion_type()
Get the type of completion being attempted. This returns the rl_completion_type variable in the underlying library as an integer. | python.library.readline#readline.get_completion_type |
readline.get_current_history_length()
Return the number of items currently in the history. (This is different from get_history_length(), which returns the maximum number of lines that will be written to a history file.) | python.library.readline#readline.get_current_history_length |
readline.get_begidx()
readline.get_endidx()
Get the beginning or ending index of the completion scope. These indexes are the start and end arguments passed to the rl_attempted_completion_function callback of the underlying library. | python.library.readline#readline.get_endidx |
readline.get_history_item(index)
Return the current contents of history item at index. The item index is one-based. This calls history_get() in the underlying library. | python.library.readline#readline.get_history_item |
readline.get_history_length()
readline.set_history_length(length)
Set or return the desired number of lines to save in the history file. The write_history_file() function uses this value to truncate the history file, by calling history_truncate_file() in the underlying library. Negative values imply unlimited history file size. | python.library.readline#readline.get_history_length |
readline.get_line_buffer()
Return the current contents of the line buffer (rl_line_buffer in the underlying library). | python.library.readline#readline.get_line_buffer |
readline.insert_text(string)
Insert text into the line buffer at the cursor position. This calls rl_insert_text() in the underlying library, but ignores the return value. | python.library.readline#readline.insert_text |
readline.parse_and_bind(string)
Execute the init line provided in the string argument. This calls rl_parse_and_bind() in the underlying library. | python.library.readline#readline.parse_and_bind |
readline.read_history_file([filename])
Load a readline history file, and append it to the history list. The default filename is ~/.history. This calls read_history() in the underlying library. | python.library.readline#readline.read_history_file |
readline.read_init_file([filename])
Execute a readline initialization file. The default filename is the last filename used. This calls rl_read_init_file() in the underlying library. | python.library.readline#readline.read_init_file |
readline.redisplay()
Change what’s displayed on the screen to reflect the current contents of the line buffer. This calls rl_redisplay() in the underlying library. | python.library.readline#readline.redisplay |
readline.remove_history_item(pos)
Remove history item specified by its position from the history. The position is zero-based. This calls remove_history() in the underlying library. | python.library.readline#readline.remove_history_item |
readline.replace_history_item(pos, line)
Replace history item specified by its position with line. The position is zero-based. This calls replace_history_entry() in the underlying library. | python.library.readline#readline.replace_history_item |
readline.set_auto_history(enabled)
Enable or disable automatic calls to add_history() when reading input via readline. The enabled argument should be a Boolean value that when true, enables auto history, and that when false, disables auto history. New in version 3.6. CPython implementation detail: Auto history is enabled by default, and changes to this do not persist across multiple sessions. | python.library.readline#readline.set_auto_history |
readline.set_completer([function])
Set or remove the completer function. If function is specified, it will be used as the new completer function; if omitted or None, any completer function already installed is removed. The completer function is called as function(text, state), for state in 0, 1, 2, …, until it returns a non-string value. It should return the next possible completion starting with text. The installed completer function is invoked by the entry_func callback passed to rl_completion_matches() in the underlying library. The text string comes from the first parameter to the rl_attempted_completion_function callback of the underlying library. | python.library.readline#readline.set_completer |
readline.set_completer_delims(string)
readline.get_completer_delims()
Set or get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the rl_completer_word_break_characters variable in the underlying library. | python.library.readline#readline.set_completer_delims |
readline.set_completion_display_matches_hook([function])
Set or remove the completion display function. If function is specified, it will be used as the new completion display function; if omitted or None, any completion display function already installed is removed. This sets or clears the rl_completion_display_matches_hook callback in the underlying library. The completion display function is called as function(substitution, [matches], longest_match_length) once each time matches need to be displayed. | python.library.readline#readline.set_completion_display_matches_hook |
readline.get_history_length()
readline.set_history_length(length)
Set or return the desired number of lines to save in the history file. The write_history_file() function uses this value to truncate the history file, by calling history_truncate_file() in the underlying library. Negative values imply unlimited history file size. | python.library.readline#readline.set_history_length |
readline.set_pre_input_hook([function])
Set or remove the function invoked by the rl_pre_input_hook callback of the underlying library. If function is specified, it will be used as the new hook function; if omitted or None, any function already installed is removed. The hook is called with no arguments after the first prompt has been printed and just before readline starts reading input characters. This function only exists if Python was compiled for a version of the library that supports it. | python.library.readline#readline.set_pre_input_hook |
readline.set_startup_hook([function])
Set or remove the function invoked by the rl_startup_hook callback of the underlying library. If function is specified, it will be used as the new hook function; if omitted or None, any function already installed is removed. The hook is called with no arguments just before readline prints the first prompt. | python.library.readline#readline.set_startup_hook |
readline.write_history_file([filename])
Save the history list to a readline history file, overwriting any existing file. The default filename is ~/.history. This calls write_history() in the underlying library. | python.library.readline#readline.write_history_file |
exception RecursionError
This exception is derived from RuntimeError. It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded. New in version 3.5: Previously, a plain RuntimeError was raised. | python.library.exceptions#RecursionError |
exception ReferenceError
This exception is raised when a weak reference proxy, created by the weakref.proxy() function, is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see the weakref module. | python.library.exceptions#ReferenceError |
repr(object)
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method. | python.library.functions#repr |
reprlib — Alternate repr() implementation Source code: Lib/reprlib.py The reprlib module provides a means for producing object representations with limits on the size of the resulting strings. This is used in the Python debugger and may be useful in other contexts as well. This module provides a class, an instance, and a function:
class reprlib.Repr
Class which provides formatting services useful in implementing functions similar to the built-in repr(); size limits for different object types are added to avoid the generation of representations which are excessively long.
reprlib.aRepr
This is an instance of Repr which is used to provide the repr() function described below. Changing the attributes of this object will affect the size limits used by repr() and the Python debugger.
reprlib.repr(obj)
This is the repr() method of aRepr. It returns a string similar to that returned by the built-in function of the same name, but with limits on most sizes.
In addition to size-limiting tools, the module also provides a decorator for detecting recursive calls to __repr__() and substituting a placeholder string instead.
@reprlib.recursive_repr(fillvalue="...")
Decorator for __repr__() methods to detect recursive calls within the same thread. If a recursive call is made, the fillvalue is returned, otherwise, the usual __repr__() call is made. For example: >>> from reprlib import recursive_repr
>>> class MyList(list):
... @recursive_repr()
... def __repr__(self):
... return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
New in version 3.2.
Repr Objects Repr instances provide several attributes which can be used to provide size limits for the representations of different object types, and methods which format specific object types.
Repr.maxlevel
Depth limit on the creation of recursive representations. The default is 6.
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others.
Repr.maxlong
Maximum number of characters in the representation for an integer. Digits are dropped from the middle. The default is 40.
Repr.maxstring
Limit on the number of characters in the representation of the string. Note that the “normal” representation of the string is used as the character source: if escape sequences are needed in the representation, these may be mangled when the representation is shortened. The default is 30.
Repr.maxother
This limit is used to control the size of object types for which no specific formatting method is available on the Repr object. It is applied in a similar manner as maxstring. The default is 20.
Repr.repr(obj)
The equivalent to the built-in repr() that uses the formatting imposed by the instance.
Repr.repr1(obj, level)
Recursive implementation used by repr(). This uses the type of obj to determine which formatting method to call, passing it obj and level. The type-specific methods should call repr1() to perform recursive formatting, with level - 1 for the value of level in the recursive call.
Repr.repr_TYPE(obj, level)
Formatting methods for specific types are implemented as methods with a name based on the type name. In the method name, TYPE is replaced by '_'.join(type(obj).__name__.split()). Dispatch to these methods is handled by repr1(). Type-specific methods which need to recursively format a value should call self.repr1(subobj, level - 1).
Subclassing Repr Objects The use of dynamic dispatching by Repr.repr1() allows subclasses of Repr to add support for additional built-in object types or to modify the handling of types already supported. This example shows how special support for file objects could be added: import reprlib
import sys
class MyRepr(reprlib.Repr):
def repr_TextIOWrapper(self, obj, level):
if obj.name in {'<stdin>', '<stdout>', '<stderr>'}:
return obj.name
return repr(obj)
aRepr = MyRepr()
print(aRepr.repr(sys.stdin)) # prints '<stdin>' | python.library.reprlib |
reprlib.aRepr
This is an instance of Repr which is used to provide the repr() function described below. Changing the attributes of this object will affect the size limits used by repr() and the Python debugger. | python.library.reprlib#reprlib.aRepr |
@reprlib.recursive_repr(fillvalue="...")
Decorator for __repr__() methods to detect recursive calls within the same thread. If a recursive call is made, the fillvalue is returned, otherwise, the usual __repr__() call is made. For example: >>> from reprlib import recursive_repr
>>> class MyList(list):
... @recursive_repr()
... def __repr__(self):
... return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
New in version 3.2. | python.library.reprlib#reprlib.recursive_repr |
class reprlib.Repr
Class which provides formatting services useful in implementing functions similar to the built-in repr(); size limits for different object types are added to avoid the generation of representations which are excessively long. | python.library.reprlib#reprlib.Repr |
reprlib.repr(obj)
This is the repr() method of aRepr. It returns a string similar to that returned by the built-in function of the same name, but with limits on most sizes. | python.library.reprlib#reprlib.repr |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxarray |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxdeque |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxdict |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxfrozenset |
Repr.maxlevel
Depth limit on the creation of recursive representations. The default is 6. | python.library.reprlib#reprlib.Repr.maxlevel |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxlist |
Repr.maxlong
Maximum number of characters in the representation for an integer. Digits are dropped from the middle. The default is 40. | python.library.reprlib#reprlib.Repr.maxlong |
Repr.maxother
This limit is used to control the size of object types for which no specific formatting method is available on the Repr object. It is applied in a similar manner as maxstring. The default is 20. | python.library.reprlib#reprlib.Repr.maxother |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxset |
Repr.maxstring
Limit on the number of characters in the representation of the string. Note that the “normal” representation of the string is used as the character source: if escape sequences are needed in the representation, these may be mangled when the representation is shortened. The default is 30. | python.library.reprlib#reprlib.Repr.maxstring |
Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray
Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others. | python.library.reprlib#reprlib.Repr.maxtuple |
Repr.repr(obj)
The equivalent to the built-in repr() that uses the formatting imposed by the instance. | python.library.reprlib#reprlib.Repr.repr |
Repr.repr1(obj, level)
Recursive implementation used by repr(). This uses the type of obj to determine which formatting method to call, passing it obj and level. The type-specific methods should call repr1() to perform recursive formatting, with level - 1 for the value of level in the recursive call. | python.library.reprlib#reprlib.Repr.repr1 |
BaseHandler.<protocol>_request(req)
This method is not defined in BaseHandler, but subclasses should define it if they want to pre-process requests of the given protocol. This method, if defined, will be called by the parent OpenerDirector. req will be a Request object. The return value should be a Request object. | python.library.urllib.request#request |
resource — Resource usage information This module provides basic mechanisms for measuring and controlling system resources utilized by a program. Symbolic constants are used to specify particular system resources and to request usage information about either the current process or its children. An OSError is raised on syscall failure.
exception resource.error
A deprecated alias of OSError. Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError.
Resource Limits Resources usage can be limited using the setrlimit() function described below. Each resource is controlled by a pair of limits: a soft limit and a hard limit. The soft limit is the current limit, and may be lowered or raised by a process over time. The soft limit can never exceed the hard limit. The hard limit can be lowered to any value greater than the soft limit, but not raised. (Only processes with the effective UID of the super-user can raise a hard limit.) The specific resources that can be limited are system dependent. They are described in the getrlimit(2) man page. The resources listed below are supported when the underlying operating system supports them; resources which cannot be checked or controlled by the operating system are not defined in this module for those platforms.
resource.RLIM_INFINITY
Constant used to represent the limit for an unlimited resource.
resource.getrlimit(resource)
Returns a tuple (soft, hard) with the current soft and hard limits of resource. Raises ValueError if an invalid resource is specified, or error if the underlying system call fails unexpectedly.
resource.setrlimit(resource, limits)
Sets new limits of consumption of resource. The limits argument must be a tuple (soft, hard) of two integers describing the new limits. A value of RLIM_INFINITY can be used to request a limit that is unlimited. Raises ValueError if an invalid resource is specified, if the new soft limit exceeds the hard limit, or if a process tries to raise its hard limit. Specifying a limit of RLIM_INFINITY when the hard or system limit for that resource is not unlimited will result in a ValueError. A process with the effective UID of super-user can request any valid limit value, including unlimited, but ValueError will still be raised if the requested limit exceeds the system imposed limit. setrlimit may also raise error if the underlying system call fails. VxWorks only supports setting RLIMIT_NOFILE. Raises an auditing event resource.setrlimit with arguments resource, limits.
resource.prlimit(pid, resource[, limits])
Combines setrlimit() and getrlimit() in one function and supports to get and set the resources limits of an arbitrary process. If pid is 0, then the call applies to the current process. resource and limits have the same meaning as in setrlimit(), except that limits is optional. When limits is not given the function returns the resource limit of the process pid. When limits is given the resource limit of the process is set and the former resource limit is returned. Raises ProcessLookupError when pid can’t be found and PermissionError when the user doesn’t have CAP_SYS_RESOURCE for the process. Raises an auditing event resource.prlimit with arguments pid, resource, limits. Availability: Linux 2.6.36 or later with glibc 2.13 or later. New in version 3.4.
These symbols define resources whose consumption can be controlled using the setrlimit() and getrlimit() functions described below. The values of these symbols are exactly the constants used by C programs. The Unix man page for getrlimit(2) lists the available resources. Note that not all systems use the same symbol or same value to denote the same resource. This module does not attempt to mask platform differences — symbols not defined for a platform will not be available from this module on that platform.
resource.RLIMIT_CORE
The maximum size (in bytes) of a core file that the current process can create. This may result in the creation of a partial core file if a larger core would be required to contain the entire process image.
resource.RLIMIT_CPU
The maximum amount of processor time (in seconds) that a process can use. If this limit is exceeded, a SIGXCPU signal is sent to the process. (See the signal module documentation for information about how to catch this signal and do something useful, e.g. flush open files to disk.)
resource.RLIMIT_FSIZE
The maximum size of a file which the process may create.
resource.RLIMIT_DATA
The maximum size (in bytes) of the process’s heap.
resource.RLIMIT_STACK
The maximum size (in bytes) of the call stack for the current process. This only affects the stack of the main thread in a multi-threaded process.
resource.RLIMIT_RSS
The maximum resident set size that should be made available to the process.
resource.RLIMIT_NPROC
The maximum number of processes the current process may create.
resource.RLIMIT_NOFILE
The maximum number of open file descriptors for the current process.
resource.RLIMIT_OFILE
The BSD name for RLIMIT_NOFILE.
resource.RLIMIT_MEMLOCK
The maximum address space which may be locked in memory.
resource.RLIMIT_VMEM
The largest area of mapped memory which the process may occupy.
resource.RLIMIT_AS
The maximum area (in bytes) of address space which may be taken by the process.
resource.RLIMIT_MSGQUEUE
The number of bytes that can be allocated for POSIX message queues. Availability: Linux 2.6.8 or later. New in version 3.4.
resource.RLIMIT_NICE
The ceiling for the process’s nice level (calculated as 20 - rlim_cur). Availability: Linux 2.6.12 or later. New in version 3.4.
resource.RLIMIT_RTPRIO
The ceiling of the real-time priority. Availability: Linux 2.6.12 or later. New in version 3.4.
resource.RLIMIT_RTTIME
The time limit (in microseconds) on CPU time that a process can spend under real-time scheduling without making a blocking syscall. Availability: Linux 2.6.25 or later. New in version 3.4.
resource.RLIMIT_SIGPENDING
The number of signals which the process may queue. Availability: Linux 2.6.8 or later. New in version 3.4.
resource.RLIMIT_SBSIZE
The maximum size (in bytes) of socket buffer usage for this user. This limits the amount of network memory, and hence the amount of mbufs, that this user may hold at any time. Availability: FreeBSD 9 or later. New in version 3.4.
resource.RLIMIT_SWAP
The maximum size (in bytes) of the swap space that may be reserved or used by all of this user id’s processes. This limit is enforced only if bit 1 of the vm.overcommit sysctl is set. Please see tuning(7) for a complete description of this sysctl. Availability: FreeBSD 9 or later. New in version 3.4.
resource.RLIMIT_NPTS
The maximum number of pseudo-terminals created by this user id. Availability: FreeBSD 9 or later. New in version 3.4.
Resource Usage These functions are used to retrieve resource usage information:
resource.getrusage(who)
This function returns an object that describes the resources consumed by either the current process or its children, as specified by the who parameter. The who parameter should be specified using one of the RUSAGE_* constants described below. A simple example: from resource import *
import time
# a non CPU-bound task
time.sleep(3)
print(getrusage(RUSAGE_SELF))
# a CPU-bound task
for i in range(10 ** 8):
_ = 1 + 1
print(getrusage(RUSAGE_SELF))
The fields of the return value each describe how a particular system resource has been used, e.g. amount of time spent running is user mode or number of times the process was swapped out of main memory. Some values are dependent on the clock tick internal, e.g. the amount of memory the process is using. For backward compatibility, the return value is also accessible as a tuple of 16 elements. The fields ru_utime and ru_stime of the return value are floating point values representing the amount of time spent executing in user mode and the amount of time spent executing in system mode, respectively. The remaining values are integers. Consult the getrusage(2) man page for detailed information about these values. A brief summary is presented here:
Index Field Resource
0 ru_utime time in user mode (float seconds)
1 ru_stime time in system mode (float seconds)
2 ru_maxrss maximum resident set size
3 ru_ixrss shared memory size
4 ru_idrss unshared memory size
5 ru_isrss unshared stack size
6 ru_minflt page faults not requiring I/O
7 ru_majflt page faults requiring I/O
8 ru_nswap number of swap outs
9 ru_inblock block input operations
10 ru_oublock block output operations
11 ru_msgsnd messages sent
12 ru_msgrcv messages received
13 ru_nsignals signals received
14 ru_nvcsw voluntary context switches
15 ru_nivcsw involuntary context switches This function will raise a ValueError if an invalid who parameter is specified. It may also raise error exception in unusual circumstances.
resource.getpagesize()
Returns the number of bytes in a system page. (This need not be the same as the hardware page size.)
The following RUSAGE_* symbols are passed to the getrusage() function to specify which processes information should be provided for.
resource.RUSAGE_SELF
Pass to getrusage() to request resources consumed by the calling process, which is the sum of resources used by all threads in the process.
resource.RUSAGE_CHILDREN
Pass to getrusage() to request resources consumed by child processes of the calling process which have been terminated and waited for.
resource.RUSAGE_BOTH
Pass to getrusage() to request resources consumed by both the current process and child processes. May not be available on all systems.
resource.RUSAGE_THREAD
Pass to getrusage() to request resources consumed by the current thread. May not be available on all systems. New in version 3.2. | python.library.resource |
exception resource.error
A deprecated alias of OSError. Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError. | python.library.resource#resource.error |
resource.getpagesize()
Returns the number of bytes in a system page. (This need not be the same as the hardware page size.) | python.library.resource#resource.getpagesize |
resource.getrlimit(resource)
Returns a tuple (soft, hard) with the current soft and hard limits of resource. Raises ValueError if an invalid resource is specified, or error if the underlying system call fails unexpectedly. | python.library.resource#resource.getrlimit |
resource.getrusage(who)
This function returns an object that describes the resources consumed by either the current process or its children, as specified by the who parameter. The who parameter should be specified using one of the RUSAGE_* constants described below. A simple example: from resource import *
import time
# a non CPU-bound task
time.sleep(3)
print(getrusage(RUSAGE_SELF))
# a CPU-bound task
for i in range(10 ** 8):
_ = 1 + 1
print(getrusage(RUSAGE_SELF))
The fields of the return value each describe how a particular system resource has been used, e.g. amount of time spent running is user mode or number of times the process was swapped out of main memory. Some values are dependent on the clock tick internal, e.g. the amount of memory the process is using. For backward compatibility, the return value is also accessible as a tuple of 16 elements. The fields ru_utime and ru_stime of the return value are floating point values representing the amount of time spent executing in user mode and the amount of time spent executing in system mode, respectively. The remaining values are integers. Consult the getrusage(2) man page for detailed information about these values. A brief summary is presented here:
Index Field Resource
0 ru_utime time in user mode (float seconds)
1 ru_stime time in system mode (float seconds)
2 ru_maxrss maximum resident set size
3 ru_ixrss shared memory size
4 ru_idrss unshared memory size
5 ru_isrss unshared stack size
6 ru_minflt page faults not requiring I/O
7 ru_majflt page faults requiring I/O
8 ru_nswap number of swap outs
9 ru_inblock block input operations
10 ru_oublock block output operations
11 ru_msgsnd messages sent
12 ru_msgrcv messages received
13 ru_nsignals signals received
14 ru_nvcsw voluntary context switches
15 ru_nivcsw involuntary context switches This function will raise a ValueError if an invalid who parameter is specified. It may also raise error exception in unusual circumstances. | python.library.resource#resource.getrusage |
resource.prlimit(pid, resource[, limits])
Combines setrlimit() and getrlimit() in one function and supports to get and set the resources limits of an arbitrary process. If pid is 0, then the call applies to the current process. resource and limits have the same meaning as in setrlimit(), except that limits is optional. When limits is not given the function returns the resource limit of the process pid. When limits is given the resource limit of the process is set and the former resource limit is returned. Raises ProcessLookupError when pid can’t be found and PermissionError when the user doesn’t have CAP_SYS_RESOURCE for the process. Raises an auditing event resource.prlimit with arguments pid, resource, limits. Availability: Linux 2.6.36 or later with glibc 2.13 or later. New in version 3.4. | python.library.resource#resource.prlimit |
resource.RLIMIT_AS
The maximum area (in bytes) of address space which may be taken by the process. | python.library.resource#resource.RLIMIT_AS |
resource.RLIMIT_CORE
The maximum size (in bytes) of a core file that the current process can create. This may result in the creation of a partial core file if a larger core would be required to contain the entire process image. | python.library.resource#resource.RLIMIT_CORE |
resource.RLIMIT_CPU
The maximum amount of processor time (in seconds) that a process can use. If this limit is exceeded, a SIGXCPU signal is sent to the process. (See the signal module documentation for information about how to catch this signal and do something useful, e.g. flush open files to disk.) | python.library.resource#resource.RLIMIT_CPU |
resource.RLIMIT_DATA
The maximum size (in bytes) of the process’s heap. | python.library.resource#resource.RLIMIT_DATA |
resource.RLIMIT_FSIZE
The maximum size of a file which the process may create. | python.library.resource#resource.RLIMIT_FSIZE |
resource.RLIMIT_MEMLOCK
The maximum address space which may be locked in memory. | python.library.resource#resource.RLIMIT_MEMLOCK |
resource.RLIMIT_MSGQUEUE
The number of bytes that can be allocated for POSIX message queues. Availability: Linux 2.6.8 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_MSGQUEUE |
resource.RLIMIT_NICE
The ceiling for the process’s nice level (calculated as 20 - rlim_cur). Availability: Linux 2.6.12 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_NICE |
resource.RLIMIT_NOFILE
The maximum number of open file descriptors for the current process. | python.library.resource#resource.RLIMIT_NOFILE |
resource.RLIMIT_NPROC
The maximum number of processes the current process may create. | python.library.resource#resource.RLIMIT_NPROC |
resource.RLIMIT_NPTS
The maximum number of pseudo-terminals created by this user id. Availability: FreeBSD 9 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_NPTS |
resource.RLIMIT_OFILE
The BSD name for RLIMIT_NOFILE. | python.library.resource#resource.RLIMIT_OFILE |
resource.RLIMIT_RSS
The maximum resident set size that should be made available to the process. | python.library.resource#resource.RLIMIT_RSS |
resource.RLIMIT_RTPRIO
The ceiling of the real-time priority. Availability: Linux 2.6.12 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_RTPRIO |
resource.RLIMIT_RTTIME
The time limit (in microseconds) on CPU time that a process can spend under real-time scheduling without making a blocking syscall. Availability: Linux 2.6.25 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_RTTIME |
resource.RLIMIT_SBSIZE
The maximum size (in bytes) of socket buffer usage for this user. This limits the amount of network memory, and hence the amount of mbufs, that this user may hold at any time. Availability: FreeBSD 9 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_SBSIZE |
resource.RLIMIT_SIGPENDING
The number of signals which the process may queue. Availability: Linux 2.6.8 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_SIGPENDING |
resource.RLIMIT_STACK
The maximum size (in bytes) of the call stack for the current process. This only affects the stack of the main thread in a multi-threaded process. | python.library.resource#resource.RLIMIT_STACK |
resource.RLIMIT_SWAP
The maximum size (in bytes) of the swap space that may be reserved or used by all of this user id’s processes. This limit is enforced only if bit 1 of the vm.overcommit sysctl is set. Please see tuning(7) for a complete description of this sysctl. Availability: FreeBSD 9 or later. New in version 3.4. | python.library.resource#resource.RLIMIT_SWAP |
resource.RLIMIT_VMEM
The largest area of mapped memory which the process may occupy. | python.library.resource#resource.RLIMIT_VMEM |
resource.RLIM_INFINITY
Constant used to represent the limit for an unlimited resource. | python.library.resource#resource.RLIM_INFINITY |
resource.RUSAGE_BOTH
Pass to getrusage() to request resources consumed by both the current process and child processes. May not be available on all systems. | python.library.resource#resource.RUSAGE_BOTH |
resource.RUSAGE_CHILDREN
Pass to getrusage() to request resources consumed by child processes of the calling process which have been terminated and waited for. | python.library.resource#resource.RUSAGE_CHILDREN |
resource.RUSAGE_SELF
Pass to getrusage() to request resources consumed by the calling process, which is the sum of resources used by all threads in the process. | python.library.resource#resource.RUSAGE_SELF |
resource.RUSAGE_THREAD
Pass to getrusage() to request resources consumed by the current thread. May not be available on all systems. New in version 3.2. | python.library.resource#resource.RUSAGE_THREAD |
resource.setrlimit(resource, limits)
Sets new limits of consumption of resource. The limits argument must be a tuple (soft, hard) of two integers describing the new limits. A value of RLIM_INFINITY can be used to request a limit that is unlimited. Raises ValueError if an invalid resource is specified, if the new soft limit exceeds the hard limit, or if a process tries to raise its hard limit. Specifying a limit of RLIM_INFINITY when the hard or system limit for that resource is not unlimited will result in a ValueError. A process with the effective UID of super-user can request any valid limit value, including unlimited, but ValueError will still be raised if the requested limit exceeds the system imposed limit. setrlimit may also raise error if the underlying system call fails. VxWorks only supports setting RLIMIT_NOFILE. Raises an auditing event resource.setrlimit with arguments resource, limits. | python.library.resource#resource.setrlimit |
exception ResourceWarning
Base class for warnings related to resource usage. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. New in version 3.2. | python.library.exceptions#ResourceWarning |
BaseHandler.<protocol>_response(req, response)
This method is not defined in BaseHandler, but subclasses should define it if they want to post-process responses of the given protocol. This method, if defined, will be called by the parent OpenerDirector. req will be a Request object. response will be an object implementing the same interface as the return value of urlopen(). The return value should implement the same interface as the return value of urlopen(). | python.library.urllib.request#response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.