doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
max(other, context=None) Like max(self, other) except that the context rounding rule is applied before returning and that NaN values are either signaled or ignored (depending on the context and whether they are signaling or quiet).
python.library.decimal#decimal.Decimal.max
max_mag(other, context=None) Similar to the max() method, but the comparison is done using the absolute values of the operands.
python.library.decimal#decimal.Decimal.max_mag
min(other, context=None) Like min(self, other) except that the context rounding rule is applied before returning and that NaN values are either signaled or ignored (depending on the context and whether they are signaling or quiet).
python.library.decimal#decimal.Decimal.min
min_mag(other, context=None) Similar to the min() method, but the comparison is done using the absolute values of the operands.
python.library.decimal#decimal.Decimal.min_mag
next_minus(context=None) Return the largest number representable in the given context (or in the current thread’s context if no context is given) that is smaller than the given operand.
python.library.decimal#decimal.Decimal.next_minus
next_plus(context=None) Return the smallest number representable in the given context (or in the current thread’s context if no context is given) that is larger than the given operand.
python.library.decimal#decimal.Decimal.next_plus
next_toward(other, context=None) If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.
python.library.decimal#decimal.Decimal.next_toward
normalize(context=None) Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0'). Used for producing canonical values for attributes of an equivalence class. For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent value Decimal('32.1').
python.library.decimal#decimal.Decimal.normalize
number_class(context=None) Return a string describing the class of the operand. The returned value is one of the following ten strings. "-Infinity", indicating that the operand is negative infinity. "-Normal", indicating that the operand is a negative normal number. "-Subnormal", indicating that the operand is negative and subnormal. "-Zero", indicating that the operand is a negative zero. "+Zero", indicating that the operand is a positive zero. "+Subnormal", indicating that the operand is positive and subnormal. "+Normal", indicating that the operand is a positive normal number. "+Infinity", indicating that the operand is positive infinity. "NaN", indicating that the operand is a quiet NaN (Not a Number). "sNaN", indicating that the operand is a signaling NaN.
python.library.decimal#decimal.Decimal.number_class
quantize(exp, rounding=None, context=None) Return a value equal to the first operand after rounding and having the exponent of the second operand. >>> Decimal('1.41421356').quantize(Decimal('1.000')) Decimal('1.414') Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand. Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact. If the exponent of the second operand is larger than that of the first then rounding may be necessary. In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given the rounding mode of the current thread’s context is used. An error is returned whenever the resulting exponent is greater than Emax or less than Etiny.
python.library.decimal#decimal.Decimal.quantize
radix() Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. Included for compatibility with the specification.
python.library.decimal#decimal.Decimal.radix
remainder_near(other, context=None) Return the remainder from dividing self by other. This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and if two integers are equally near then the even one is chosen. If the result is zero then its sign will be the sign of self. >>> Decimal(18).remainder_near(Decimal(10)) Decimal('-2') >>> Decimal(25).remainder_near(Decimal(10)) Decimal('5') >>> Decimal(35).remainder_near(Decimal(10)) Decimal('-5')
python.library.decimal#decimal.Decimal.remainder_near
rotate(other, context=None) Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right. The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.
python.library.decimal#decimal.Decimal.rotate
same_quantum(other, context=None) Test whether self and other have the same exponent or whether both are NaN. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
python.library.decimal#decimal.Decimal.same_quantum
scaleb(other, context=None) Return the first operand with exponent adjusted by the second. Equivalently, return the first operand multiplied by 10**other. The second operand must be an integer.
python.library.decimal#decimal.Decimal.scaleb
shift(other, context=None) Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.
python.library.decimal#decimal.Decimal.shift
sqrt(context=None) Return the square root of the argument to full precision.
python.library.decimal#decimal.Decimal.sqrt
to_eng_string(context=None) Convert to a string, using engineering notation if an exponent is needed. Engineering notation has an exponent which is a multiple of 3. This can leave up to 3 digits to the left of the decimal place and may require the addition of either one or two trailing zeros. For example, this converts Decimal('123E+1') to Decimal('1.23E+3').
python.library.decimal#decimal.Decimal.to_eng_string
to_integral(rounding=None, context=None) Identical to the to_integral_value() method. The to_integral name has been kept for compatibility with older versions.
python.library.decimal#decimal.Decimal.to_integral
to_integral_exact(rounding=None, context=None) Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given then the rounding mode of the current context is used.
python.library.decimal#decimal.Decimal.to_integral_exact
to_integral_value(rounding=None, context=None) Round to the nearest integer without signaling Inexact or Rounded. If given, applies rounding; otherwise, uses the rounding method in either the supplied context or the current context.
python.library.decimal#decimal.Decimal.to_integral_value
class decimal.DecimalException Base class for other signals and a subclass of ArithmeticError.
python.library.decimal#decimal.DecimalException
class decimal.DefaultContext This context is used by the Context constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the default for new contexts created by the Context constructor. This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide defaults. Changing the fields after threads have started is not recommended as it would require thread synchronization to prevent race conditions. In single threaded environments, it is preferable to not use this context at all. Instead, simply create contexts explicitly as described below. The default values are prec=28, rounding=ROUND_HALF_EVEN, and enabled traps for Overflow, InvalidOperation, and DivisionByZero.
python.library.decimal#decimal.DefaultContext
class decimal.DivisionByZero Signals the division of a non-infinite number by zero. Can occur with division, modulo division, or when raising a number to a negative power. If this signal is not trapped, returns Infinity or -Infinity with the sign determined by the inputs to the calculation.
python.library.decimal#decimal.DivisionByZero
class decimal.ExtendedContext This is a standard context defined by the General Decimal Arithmetic Specification. Precision is set to nine. Rounding is set to ROUND_HALF_EVEN. All flags are cleared. No traps are enabled (so that exceptions are not raised during computations). Because the traps are disabled, this context is useful for applications that prefer to have result value of NaN or Infinity instead of raising exceptions. This allows an application to complete a run in the presence of conditions that would otherwise halt the program.
python.library.decimal#decimal.ExtendedContext
class decimal.FloatOperation Enable stricter semantics for mixing floats and Decimals. If the signal is not trapped (default), mixing floats and Decimals is permitted in the Decimal constructor, create_decimal() and all comparison operators. Both conversion and comparisons are exact. Any occurrence of a mixed operation is silently recorded by setting FloatOperation in the context flags. Explicit conversions with from_float() or create_decimal_from_float() do not set the flag. Otherwise (the signal is trapped), only equality comparisons and explicit conversions are silent. All other mixed operations raise FloatOperation.
python.library.decimal#decimal.FloatOperation
decimal.getcontext() Return the current context for the active thread.
python.library.decimal#decimal.getcontext
decimal.HAVE_CONTEXTVAR The default value is True. If Python is compiled --without-decimal-contextvar, the C version uses a thread-local rather than a coroutine-local context and the value is False. This is slightly faster in some nested context scenarios.
python.library.decimal#decimal.HAVE_CONTEXTVAR
decimal.HAVE_THREADS The value is True. Deprecated, because Python now always has threads.
python.library.decimal#decimal.HAVE_THREADS
class decimal.Inexact Indicates that rounding occurred and the result is not exact. Signals when non-zero digits were discarded during rounding. The rounded result is returned. The signal flag or trap is used to detect when results are inexact.
python.library.decimal#decimal.Inexact
class decimal.InvalidOperation An invalid operation was performed. Indicates that an operation was requested that does not make sense. If not trapped, returns NaN. Possible causes include: Infinity - Infinity 0 * Infinity Infinity / Infinity x % 0 Infinity % x sqrt(-x) and x > 0 0 ** 0 x ** (non-integer) x ** Infinity
python.library.decimal#decimal.InvalidOperation
decimal.localcontext(ctx=None) Return a context manager that will set the current context for the active thread to a copy of ctx on entry to the with-statement and restore the previous context when exiting the with-statement. If no context is specified, a copy of the current context is used. For example, the following code sets the current decimal precision to 42 places, performs a calculation, and then automatically restores the previous context: from decimal import localcontext with localcontext() as ctx: ctx.prec = 42 # Perform a high precision calculation s = calculate_something() s = +s # Round the final result back to the default precision
python.library.decimal#decimal.localcontext
decimal.MAX_EMAX
python.library.decimal#decimal.MAX_EMAX
decimal.MAX_PREC
python.library.decimal#decimal.MAX_PREC
decimal.MIN_EMIN
python.library.decimal#decimal.MIN_EMIN
decimal.MIN_ETINY
python.library.decimal#decimal.MIN_ETINY
class decimal.Overflow Numerical overflow. Indicates the exponent is larger than Emax after rounding has occurred. If not trapped, the result depends on the rounding mode, either pulling inward to the largest representable finite number or rounding outward to Infinity. In either case, Inexact and Rounded are also signaled.
python.library.decimal#decimal.Overflow
class decimal.Rounded Rounding occurred though possibly no information was lost. Signaled whenever rounding discards digits; even if those digits are zero (such as rounding 5.00 to 5.0). If not trapped, returns the result unchanged. This signal is used to detect loss of significant digits.
python.library.decimal#decimal.Rounded
decimal.ROUND_05UP Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero.
python.library.decimal#decimal.ROUND_05UP
decimal.ROUND_CEILING Round towards Infinity.
python.library.decimal#decimal.ROUND_CEILING
decimal.ROUND_DOWN Round towards zero.
python.library.decimal#decimal.ROUND_DOWN
decimal.ROUND_FLOOR Round towards -Infinity.
python.library.decimal#decimal.ROUND_FLOOR
decimal.ROUND_HALF_DOWN Round to nearest with ties going towards zero.
python.library.decimal#decimal.ROUND_HALF_DOWN
decimal.ROUND_HALF_EVEN Round to nearest with ties going to nearest even integer.
python.library.decimal#decimal.ROUND_HALF_EVEN
decimal.ROUND_HALF_UP Round to nearest with ties going away from zero.
python.library.decimal#decimal.ROUND_HALF_UP
decimal.ROUND_UP Round away from zero.
python.library.decimal#decimal.ROUND_UP
decimal.setcontext(c) Set the current context for the active thread to c.
python.library.decimal#decimal.setcontext
class decimal.Subnormal Exponent was lower than Emin prior to rounding. Occurs when an operation result is subnormal (the exponent is too small). If not trapped, returns the result unchanged.
python.library.decimal#decimal.Subnormal
class decimal.Underflow Numerical underflow with result rounded to zero. Occurs when a subnormal result is pushed to zero by rounding. Inexact and Subnormal are also signaled.
python.library.decimal#decimal.Underflow
definition.__name__ The name of the class, function, method, descriptor, or generator instance.
python.library.stdtypes#definition.__name__
definition.__qualname__ The qualified name of the class, function, method, descriptor, or generator instance. New in version 3.3.
python.library.stdtypes#definition.__qualname__
delattr(object, name) This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.
python.library.functions#delattr
exception DeprecationWarning Base class for warnings about deprecated features when those warnings are intended for other Python developers. Ignored by the default warning filters, except in the __main__ module (PEP 565). Enabling the Python Development Mode shows this warning.
python.library.exceptions#DeprecationWarning
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class. For other containers see the built-in list, set, and tuple classes, as well as the collections module.
python.library.functions#dict
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments. Dictionaries can be created by several means: Use a comma-separated list of key: value pairs within braces: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'} Use a dict comprehension: {}, {x: x ** 2 for x in range(10)} Use the type constructor: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200) If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary. If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument. To illustrate, the following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3}: >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used. These are the operations that dictionaries support (and therefore, custom mapping types should support too): list(d) Return a list of all the keys used in the dictionary d. len(d) Return the number of items in the dictionary d. d[key] Return the item of d with key key. Raises a KeyError if key is not in the map. If a subclass of dict defines a method __missing__() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable: >>> class Counter(dict): ... def __missing__(self, key): ... return 0 >>> c = Counter() >>> c['red'] 0 >>> c['red'] += 1 >>> c['red'] 1 The example above shows part of the implementation of collections.Counter. A different __missing__ method is used by collections.defaultdict. d[key] = value Set d[key] to value. del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map. key in d Return True if d has a key key, else False. key not in d Equivalent to not key in d. iter(d) Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()). clear() Remove all items from the dictionary. copy() Return a shallow copy of the dictionary. classmethod fromkeys(iterable[, value]) Create a new dictionary with keys from iterable and values set to value. fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead. get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. items() Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects. keys() Return a new view of the dictionary’s keys. See the documentation of view objects. pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised. popitem() Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError. Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair. reversed(d) Return a reverse iterator over the keys of the dictionary. This is a shortcut for reversed(d.keys()). New in version 3.8. setdefault(key[, default]) If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None. update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2). values() Return a new view of the dictionary’s values. See the documentation of view objects. An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself: >>> d = {'a': 1} >>> d.values() == d.values() False d | other Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys. New in version 3.9. d |= other Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys. New in version 3.9. Dictionaries compare equal if and only if they have the same (key, value) pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError. Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end. >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(d) ['one', 'two', 'three', 'four'] >>> list(d.values()) [1, 2, 3, 4] >>> d["one"] = 42 >>> d {'one': 42, 'two': 2, 'three': 3, 'four': 4} >>> del d["two"] >>> d["two"] = None >>> d {'one': 42, 'three': 3, 'four': 4, 'two': None} Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6. Dictionaries and dictionary views are reversible. >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(reversed(d)) ['four', 'three', 'two', 'one'] >>> list(reversed(d.values())) [4, 3, 2, 1] >>> list(reversed(d.items())) [('four', 4), ('three', 3), ('two', 2), ('one', 1)] Changed in version 3.8: Dictionaries are now reversible.
python.library.stdtypes#dict
clear() Remove all items from the dictionary.
python.library.stdtypes#dict.clear
copy() Return a shallow copy of the dictionary.
python.library.stdtypes#dict.copy
classmethod fromkeys(iterable[, value]) Create a new dictionary with keys from iterable and values set to value. fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.
python.library.stdtypes#dict.fromkeys
get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
python.library.stdtypes#dict.get
items() Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.
python.library.stdtypes#dict.items
keys() Return a new view of the dictionary’s keys. See the documentation of view objects.
python.library.stdtypes#dict.keys
pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
python.library.stdtypes#dict.pop
popitem() Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError. Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.
python.library.stdtypes#dict.popitem
setdefault(key[, default]) If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
python.library.stdtypes#dict.setdefault
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
python.library.stdtypes#dict.update
values() Return a new view of the dictionary’s values. See the documentation of view objects. An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself: >>> d = {'a': 1} >>> d.values() == d.values() False
python.library.stdtypes#dict.values
difflib — Helpers for computing deltas Source code: Lib/difflib.py This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module. class difflib.SequenceMatcher This is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980’s by Ratcliff and Obershelp under the hyperbolic name “gestalt pattern matching.” The idea is to find the longest contiguous matching subsequence that contains no “junk” elements; these “junk” elements are ones that are uninteresting in some sense, such as blank lines or whitespace. (Handling junk is an extension to the Ratcliff and Obershelp algorithm.) The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that “look right” to people. Timing: The basic Ratcliff-Obershelp algorithm is cubic time in the worst case and quadratic time in the expected case. SequenceMatcher is quadratic time for the worst case and has expected-case behavior dependent in a complicated way on how many elements the sequences have in common; best case time is linear. Automatic junk heuristic: SequenceMatcher supports a heuristic that automatically treats certain sequence items as junk. The heuristic counts how many times each individual item appears in the sequence. If an item’s duplicates (after the first one) account for more than 1% of the sequence and the sequence is at least 200 items long, this item is marked as “popular” and is treated as junk for the purpose of sequence matching. This heuristic can be turned off by setting the autojunk argument to False when creating the SequenceMatcher. New in version 3.2: The autojunk parameter. class difflib.Differ This is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses SequenceMatcher both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines. Each line of a Differ delta begins with a two-letter code: Code Meaning '- ' line unique to sequence 1 '+ ' line unique to sequence 2 '  ' line common to both sequences '? ' line not present in either input sequence Lines beginning with ‘?’ attempt to guide the eye to intraline differences, and were not present in either input sequence. These lines can be confusing if the sequences contain tab characters. class difflib.HtmlDiff This class can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights. The table can be generated in either full or contextual difference mode. The constructor for this class is: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK) Initializes instance of HtmlDiff. tabsize is an optional keyword argument to specify tab stop spacing and defaults to 8. wrapcolumn is an optional keyword to specify column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk and charjunk are optional keyword arguments passed into ndiff() (used by HtmlDiff to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions. The following methods are public: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5, *, charset='utf-8') Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML file containing a table showing line by line differences with inter-line and intra-line changes highlighted. fromdesc and todesc are optional keyword arguments to specify from/to file column header strings (both default to an empty string). context and numlines are both optional keyword arguments. Set context to True when contextual differences are to be shown, else the default is False to show the full files. numlines defaults to 5. When context is True numlines controls the number of context lines which surround the difference highlights. When context is False numlines controls the number of lines which are shown before a difference highlight when using the “next” hyperlinks (setting to zero would cause the “next” hyperlinks to place the next difference highlight at the top of the browser without any leading context). Note fromdesc and todesc are interpreted as unescaped HTML and should be properly escaped while receiving input from untrusted sources. Changed in version 3.5: charset keyword-only argument was added. The default charset of HTML document changed from 'ISO-8859-1' to 'utf-8'. make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5) Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML table showing line by line differences with inter-line and intra-line changes highlighted. The arguments for this method are the same as those for the make_file() method. Tools/scripts/diff.py is a command-line front-end to this class and contains a good example of its use. difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n') Compare a and b (lists of strings); return a delta (a generator generating the delta lines) in context diff format. Context diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a before/after style. The number of context lines is set by n which defaults to three. By default, the diff control lines (those with *** or ---) are created with a trailing newline. This is helpful so that inputs created from io.IOBase.readlines() result in diffs that are suitable for use with io.IOBase.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for fromfile, tofile, fromfiledate, and tofiledate. The modification times are normally expressed in the ISO 8601 format. If not specified, the strings default to blanks. >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py')) *** before.py --- after.py *************** *** 1,4 **** ! bacon ! eggs ! ham guido --- 1,4 ---- ! python ! eggy ! hamster guido See A command-line interface to difflib for a more detailed example. difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6) Return a list of the best “good enough” matches. word is a sequence for which close matches are desired (typically a string), and possibilities is a list of sequences against which to match word (typically a list of strings). Optional argument n (default 3) is the maximum number of close matches to return; n must be greater than 0. Optional argument cutoff (default 0.6) is a float in the range [0, 1]. Possibilities that don’t score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> get_close_matches('wheel', keyword.kwlist) ['while'] >>> get_close_matches('pineapple', keyword.kwlist) [] >>> get_close_matches('accept', keyword.kwlist) ['except'] difflib.ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK) Compare a and b (lists of strings); return a Differ-style delta (a generator generating the delta lines). Optional keyword parameters linejunk and charjunk are filtering functions (or None): linejunk: A function that accepts a single string argument, and returns true if the string is junk, or false if not. The default is None. There is also a module-level function IS_LINE_JUNK(), which filters out lines without visible characters, except for at most one pound character ('#') – however the underlying SequenceMatcher class does a dynamic analysis of which lines are so frequent as to constitute noise, and this usually works better than using this function. charjunk: A function that accepts a character (a string of length 1), and returns if the character is junk, or false if not. The default is module-level function IS_CHARACTER_JUNK(), which filters out whitespace characters (a blank or tab; it’s a bad idea to include newline in this!). Tools/scripts/ndiff.py is a command-line front-end to this function. >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) >>> print(''.join(diff), end="") - one ? ^ + ore ? ^ - two - three ? - + tree + emu difflib.restore(sequence, which) Return one of the two sequences that generated a delta. Given a sequence produced by Differ.compare() or ndiff(), extract lines originating from file 1 or 2 (parameter which), stripping off line prefixes. Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) >>> diff = list(diff) # materialize the generated delta into a list >>> print(''.join(restore(diff, 1)), end="") one two three >>> print(''.join(restore(diff, 2)), end="") ore tree emu difflib.unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n') Compare a and b (lists of strings); return a delta (a generator generating the delta lines) in unified diff format. Unified diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in an inline style (instead of separate before/after blocks). The number of context lines is set by n which defaults to three. By default, the diff control lines (those with ---, +++, or @@) are created with a trailing newline. This is helpful so that inputs created from io.IOBase.readlines() result in diffs that are suitable for use with io.IOBase.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for fromfile, tofile, fromfiledate, and tofiledate. The modification times are normally expressed in the ISO 8601 format. If not specified, the strings default to blanks. >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py')) --- before.py +++ after.py @@ -1,4 +1,4 @@ -bacon -eggs -ham +python +eggy +hamster guido See A command-line interface to difflib for a more detailed example. difflib.diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n') Compare a and b (lists of bytes objects) using dfunc; yield a sequence of delta lines (also bytes) in the format returned by dfunc. dfunc must be a callable, typically either unified_diff() or context_diff(). Allows you to compare data with unknown or inconsistent encoding. All inputs except n must be bytes objects, not str. Works by losslessly converting all inputs (except n) to str, and calling dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm). The output of dfunc is then converted back to bytes, so the delta lines that you receive have the same unknown/inconsistent encodings as a and b. New in version 3.5. difflib.IS_LINE_JUNK(line) Return True for ignorable lines. The line line is ignorable if line is blank or contains a single '#', otherwise it is not ignorable. Used as a default for parameter linejunk in ndiff() in older versions. difflib.IS_CHARACTER_JUNK(ch) Return True for ignorable characters. The character ch is ignorable if ch is a space or tab, otherwise it is not ignorable. Used as a default for parameter charjunk in ndiff(). See also Pattern Matching: The Gestalt Approach Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This was published in Dr. Dobb’s Journal in July, 1988. SequenceMatcher Objects The SequenceMatcher class has this constructor: class difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True) Optional argument isjunk must be None (the default) or a one-argument function that takes a sequence element and returns true if and only if the element is “junk” and should be ignored. Passing None for isjunk is equivalent to passing lambda x: False; in other words, no elements are ignored. For example, pass: lambda x: x in " \t" if you’re comparing lines as sequences of characters, and don’t want to synch up on blanks or hard tabs. The optional arguments a and b are sequences to be compared; both default to empty strings. The elements of both sequences must be hashable. The optional argument autojunk can be used to disable the automatic junk heuristic. New in version 3.2: The autojunk parameter. SequenceMatcher objects get three data attributes: bjunk is the set of elements of b for which isjunk is True; bpopular is the set of non-junk elements considered popular by the heuristic (if it is not disabled); b2j is a dict mapping the remaining elements of b to a list of positions where they occur. All three are reset whenever b is reset with set_seqs() or set_seq2(). New in version 3.2: The bjunk and bpopular attributes. SequenceMatcher objects have the following methods: set_seqs(a, b) Set the two sequences to be compared. SequenceMatcher computes and caches detailed information about the second sequence, so if you want to compare one sequence against many sequences, use set_seq2() to set the commonly used sequence once and call set_seq1() repeatedly, once for each of the other sequences. set_seq1(a) Set the first sequence to be compared. The second sequence to be compared is not changed. set_seq2(b) Set the second sequence to be compared. The first sequence to be compared is not changed. find_longest_match(alo=0, ahi=None, blo=0, bhi=None) Find longest matching block in a[alo:ahi] and b[blo:bhi]. If isjunk was omitted or None, find_longest_match() returns (i, j, k) such that a[i:i+k] is equal to b[j:j+k], where alo <= i <= i+k <= ahi and blo <= j <= j+k <= bhi. For all (i', j', k') meeting those conditions, the additional conditions k >= k', i <= i', and if i == i', j <= j' are also met. In other words, of all maximal matching blocks, return one that starts earliest in a, and of all those maximal matching blocks that start earliest in a, return the one that starts earliest in b. >>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=0, b=4, size=5) If isjunk was provided, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an interesting match. Here’s the same example as before, but considering blanks to be junk. That prevents ' abcd' from matching the ' abcd' at the tail end of the second sequence directly. Instead only the 'abcd' can match, and matches the leftmost 'abcd' in the second sequence: >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=1, b=0, size=4) If no blocks match, this returns (alo, blo, 0). This method returns a named tuple Match(a, b, size). Changed in version 3.9: Added default arguments. get_matching_blocks() Return list of triples describing non-overlapping matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and j. The last triple is a dummy, and has the value (len(a), len(b), 0). It is the only triple with n == 0. If (i, j, n) and (i', j', n') are adjacent triples in the list, and the second is not the last triple in the list, then i+n < i' or j+n < j'; in other words, adjacent triples always describe non-adjacent equal blocks. >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s.get_matching_blocks() [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] get_opcodes() Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 equal to the i2 from the preceding tuple, and, likewise, j1 equal to the previous j2. The tag values are strings, with these meanings: Value Meaning 'replace' a[i1:i2] should be replaced by b[j1:j2]. 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). For example: >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format( ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) delete a[0:1] --> b[0:0] 'q' --> '' equal a[1:3] --> b[0:2] 'ab' --> 'ab' replace a[3:4] --> b[2:3] 'x' --> 'y' equal a[4:6] --> b[3:5] 'cd' --> 'cd' insert a[6:6] --> b[5:6] '' --> 'f' get_grouped_opcodes(n=3) Return a generator of groups with up to n lines of context. Starting with the groups returned by get_opcodes(), this method splits out smaller change clusters and eliminates intervening ranges which have no changes. The groups are returned in the same format as get_opcodes(). ratio() Return a measure of the sequences’ similarity as a float in the range [0, 1]. Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is 1.0 if the sequences are identical, and 0.0 if they have nothing in common. This is expensive to compute if get_matching_blocks() or get_opcodes() hasn’t already been called, in which case you may want to try quick_ratio() or real_quick_ratio() first to get an upper bound. Note Caution: The result of a ratio() call may depend on the order of the arguments. For instance: >>> SequenceMatcher(None, 'tide', 'diet').ratio() 0.25 >>> SequenceMatcher(None, 'diet', 'tide').ratio() 0.5 quick_ratio() Return an upper bound on ratio() relatively quickly. real_quick_ratio() Return an upper bound on ratio() very quickly. The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although quick_ratio() and real_quick_ratio() are always at least as large as ratio(): >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.quick_ratio() 0.75 >>> s.real_quick_ratio() 1.0 SequenceMatcher Examples This example compares two strings, considering blanks to be “junk”: >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", ... "private volatile Thread currentThread;") ratio() returns a float in [0, 1], measuring the similarity of the sequences. As a rule of thumb, a ratio() value over 0.6 means the sequences are close matches: >>> print(round(s.ratio(), 3)) 0.866 If you’re only interested in where the sequences match, get_matching_blocks() is handy: >>> for block in s.get_matching_blocks(): ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements Note that the last tuple returned by get_matching_blocks() is always a dummy, (len(a), len(b), 0), and this is the only case in which the last tuple element (number of elements matched) is 0. If you want to know how to change the first sequence into the second, use get_opcodes(): >>> for opcode in s.get_opcodes(): ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] See also The get_close_matches() function in this module which shows how simple code building on SequenceMatcher can be used to do useful work. Simple version control recipe for a small application built with SequenceMatcher. Differ Objects Note that Differ-generated deltas make no claim to be minimal diffs. To the contrary, minimal diffs are often counter-intuitive, because they synch up anywhere possible, sometimes accidental matches 100 pages apart. Restricting synch points to contiguous matches preserves some notion of locality, at the occasional cost of producing a longer diff. The Differ class has this constructor: class difflib.Differ(linejunk=None, charjunk=None) Optional keyword parameters linejunk and charjunk are for filter functions (or None): linejunk: A function that accepts a single string argument, and returns true if the string is junk. The default is None, meaning that no line is considered junk. charjunk: A function that accepts a single character argument (a string of length 1), and returns true if the character is junk. The default is None, meaning that no character is considered junk. These junk-filtering functions speed up matching to find differences and do not cause any differing lines or characters to be ignored. Read the description of the find_longest_match() method’s isjunk parameter for an explanation. Differ objects are used (deltas generated) via a single method: compare(a, b) Compare two sequences of lines, and generate the delta (a sequence of lines). Each sequence must contain individual single-line strings ending with newlines. Such sequences can be obtained from the readlines() method of file-like objects. The delta generated also consists of newline-terminated strings, ready to be printed as-is via the writelines() method of a file-like object. Differ Example This example compares two texts. First we set up the texts, sequences of individual single-line strings ending with newlines (such sequences can also be obtained from the readlines() method of file-like objects): >>> text1 = ''' 1. Beautiful is better than ugly. ... 2. Explicit is better than implicit. ... 3. Simple is better than complex. ... 4. Complex is better than complicated. ... '''.splitlines(keepends=True) >>> len(text1) 4 >>> text1[0][-1] '\n' >>> text2 = ''' 1. Beautiful is better than ugly. ... 3. Simple is better than complex. ... 4. Complicated is better than complex. ... 5. Flat is better than nested. ... '''.splitlines(keepends=True) Next we instantiate a Differ object: >>> d = Differ() Note that when instantiating a Differ object we may pass functions to filter out line and character “junk.” See the Differ() constructor for details. Finally, we compare the two: >>> result = list(d.compare(text1, text2)) result is a list of strings, so let’s pretty-print it: >>> from pprint import pprint >>> pprint(result) [' 1. Beautiful is better than ugly.\n', '- 2. Explicit is better than implicit.\n', '- 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n', '? ++\n', '- 4. Complex is better than complicated.\n', '? ^ ---- ^\n', '+ 4. Complicated is better than complex.\n', '? ++++ ^ ^\n', '+ 5. Flat is better than nested.\n'] As a single multi-line string it looks like this: >>> import sys >>> sys.stdout.writelines(result) 1. Beautiful is better than ugly. - 2. Explicit is better than implicit. - 3. Simple is better than complex. + 3. Simple is better than complex. ? ++ - 4. Complex is better than complicated. ? ^ ---- ^ + 4. Complicated is better than complex. ? ++++ ^ ^ + 5. Flat is better than nested. A command-line interface to difflib This example shows how to use difflib to create a diff-like utility. It is also contained in the Python source distribution, as Tools/scripts/diff.py. #!/usr/bin/env python3 """ Command line interface to difflib.py providing diffs in four formats: * ndiff: lists every line and highlights interline changes. * context: highlights clusters of changes in a before/after format. * unified: highlights clusters of changes in an inline format. * html: generates side by side comparison with change highlights. """ import sys, os, difflib, argparse from datetime import datetime, timezone def file_mtime(path): t = datetime.fromtimestamp(os.stat(path).st_mtime, timezone.utc) return t.astimezone().isoformat() def main(): parser = argparse.ArgumentParser() parser.add_argument('-c', action='store_true', default=False, help='Produce a context format diff (default)') parser.add_argument('-u', action='store_true', default=False, help='Produce a unified format diff') parser.add_argument('-m', action='store_true', default=False, help='Produce HTML side by side diff ' '(can use -c and -l in conjunction)') parser.add_argument('-n', action='store_true', default=False, help='Produce a ndiff format diff') parser.add_argument('-l', '--lines', type=int, default=3, help='Set number of context lines (default 3)') parser.add_argument('fromfile') parser.add_argument('tofile') options = parser.parse_args() n = options.lines fromfile = options.fromfile tofile = options.tofile fromdate = file_mtime(fromfile) todate = file_mtime(tofile) with open(fromfile) as ff: fromlines = ff.readlines() with open(tofile) as tf: tolines = tf.readlines() if options.u: diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) elif options.n: diff = difflib.ndiff(fromlines, tolines) elif options.m: diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n) else: diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) sys.stdout.writelines(diff) if __name__ == '__main__': main()
python.library.difflib
difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n') Compare a and b (lists of strings); return a delta (a generator generating the delta lines) in context diff format. Context diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a before/after style. The number of context lines is set by n which defaults to three. By default, the diff control lines (those with *** or ---) are created with a trailing newline. This is helpful so that inputs created from io.IOBase.readlines() result in diffs that are suitable for use with io.IOBase.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for fromfile, tofile, fromfiledate, and tofiledate. The modification times are normally expressed in the ISO 8601 format. If not specified, the strings default to blanks. >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py')) *** before.py --- after.py *************** *** 1,4 **** ! bacon ! eggs ! ham guido --- 1,4 ---- ! python ! eggy ! hamster guido See A command-line interface to difflib for a more detailed example.
python.library.difflib#difflib.context_diff
class difflib.Differ This is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses SequenceMatcher both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines. Each line of a Differ delta begins with a two-letter code: Code Meaning '- ' line unique to sequence 1 '+ ' line unique to sequence 2 '  ' line common to both sequences '? ' line not present in either input sequence Lines beginning with ‘?’ attempt to guide the eye to intraline differences, and were not present in either input sequence. These lines can be confusing if the sequences contain tab characters.
python.library.difflib#difflib.Differ
compare(a, b) Compare two sequences of lines, and generate the delta (a sequence of lines). Each sequence must contain individual single-line strings ending with newlines. Such sequences can be obtained from the readlines() method of file-like objects. The delta generated also consists of newline-terminated strings, ready to be printed as-is via the writelines() method of a file-like object.
python.library.difflib#difflib.Differ.compare
difflib.diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n') Compare a and b (lists of bytes objects) using dfunc; yield a sequence of delta lines (also bytes) in the format returned by dfunc. dfunc must be a callable, typically either unified_diff() or context_diff(). Allows you to compare data with unknown or inconsistent encoding. All inputs except n must be bytes objects, not str. Works by losslessly converting all inputs (except n) to str, and calling dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm). The output of dfunc is then converted back to bytes, so the delta lines that you receive have the same unknown/inconsistent encodings as a and b. New in version 3.5.
python.library.difflib#difflib.diff_bytes
difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6) Return a list of the best “good enough” matches. word is a sequence for which close matches are desired (typically a string), and possibilities is a list of sequences against which to match word (typically a list of strings). Optional argument n (default 3) is the maximum number of close matches to return; n must be greater than 0. Optional argument cutoff (default 0.6) is a float in the range [0, 1]. Possibilities that don’t score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> get_close_matches('wheel', keyword.kwlist) ['while'] >>> get_close_matches('pineapple', keyword.kwlist) [] >>> get_close_matches('accept', keyword.kwlist) ['except']
python.library.difflib#difflib.get_close_matches
class difflib.HtmlDiff This class can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights. The table can be generated in either full or contextual difference mode. The constructor for this class is: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK) Initializes instance of HtmlDiff. tabsize is an optional keyword argument to specify tab stop spacing and defaults to 8. wrapcolumn is an optional keyword to specify column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk and charjunk are optional keyword arguments passed into ndiff() (used by HtmlDiff to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions. The following methods are public: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5, *, charset='utf-8') Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML file containing a table showing line by line differences with inter-line and intra-line changes highlighted. fromdesc and todesc are optional keyword arguments to specify from/to file column header strings (both default to an empty string). context and numlines are both optional keyword arguments. Set context to True when contextual differences are to be shown, else the default is False to show the full files. numlines defaults to 5. When context is True numlines controls the number of context lines which surround the difference highlights. When context is False numlines controls the number of lines which are shown before a difference highlight when using the “next” hyperlinks (setting to zero would cause the “next” hyperlinks to place the next difference highlight at the top of the browser without any leading context). Note fromdesc and todesc are interpreted as unescaped HTML and should be properly escaped while receiving input from untrusted sources. Changed in version 3.5: charset keyword-only argument was added. The default charset of HTML document changed from 'ISO-8859-1' to 'utf-8'. make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5) Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML table showing line by line differences with inter-line and intra-line changes highlighted. The arguments for this method are the same as those for the make_file() method. Tools/scripts/diff.py is a command-line front-end to this class and contains a good example of its use.
python.library.difflib#difflib.HtmlDiff
make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5, *, charset='utf-8') Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML file containing a table showing line by line differences with inter-line and intra-line changes highlighted. fromdesc and todesc are optional keyword arguments to specify from/to file column header strings (both default to an empty string). context and numlines are both optional keyword arguments. Set context to True when contextual differences are to be shown, else the default is False to show the full files. numlines defaults to 5. When context is True numlines controls the number of context lines which surround the difference highlights. When context is False numlines controls the number of lines which are shown before a difference highlight when using the “next” hyperlinks (setting to zero would cause the “next” hyperlinks to place the next difference highlight at the top of the browser without any leading context). Note fromdesc and todesc are interpreted as unescaped HTML and should be properly escaped while receiving input from untrusted sources. Changed in version 3.5: charset keyword-only argument was added. The default charset of HTML document changed from 'ISO-8859-1' to 'utf-8'.
python.library.difflib#difflib.HtmlDiff.make_file
make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5) Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML table showing line by line differences with inter-line and intra-line changes highlighted. The arguments for this method are the same as those for the make_file() method.
python.library.difflib#difflib.HtmlDiff.make_table
__init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK) Initializes instance of HtmlDiff. tabsize is an optional keyword argument to specify tab stop spacing and defaults to 8. wrapcolumn is an optional keyword to specify column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk and charjunk are optional keyword arguments passed into ndiff() (used by HtmlDiff to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions.
python.library.difflib#difflib.HtmlDiff.__init__
difflib.IS_CHARACTER_JUNK(ch) Return True for ignorable characters. The character ch is ignorable if ch is a space or tab, otherwise it is not ignorable. Used as a default for parameter charjunk in ndiff().
python.library.difflib#difflib.IS_CHARACTER_JUNK
difflib.IS_LINE_JUNK(line) Return True for ignorable lines. The line line is ignorable if line is blank or contains a single '#', otherwise it is not ignorable. Used as a default for parameter linejunk in ndiff() in older versions.
python.library.difflib#difflib.IS_LINE_JUNK
difflib.ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK) Compare a and b (lists of strings); return a Differ-style delta (a generator generating the delta lines). Optional keyword parameters linejunk and charjunk are filtering functions (or None): linejunk: A function that accepts a single string argument, and returns true if the string is junk, or false if not. The default is None. There is also a module-level function IS_LINE_JUNK(), which filters out lines without visible characters, except for at most one pound character ('#') – however the underlying SequenceMatcher class does a dynamic analysis of which lines are so frequent as to constitute noise, and this usually works better than using this function. charjunk: A function that accepts a character (a string of length 1), and returns if the character is junk, or false if not. The default is module-level function IS_CHARACTER_JUNK(), which filters out whitespace characters (a blank or tab; it’s a bad idea to include newline in this!). Tools/scripts/ndiff.py is a command-line front-end to this function. >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) >>> print(''.join(diff), end="") - one ? ^ + ore ? ^ - two - three ? - + tree + emu
python.library.difflib#difflib.ndiff
difflib.restore(sequence, which) Return one of the two sequences that generated a delta. Given a sequence produced by Differ.compare() or ndiff(), extract lines originating from file 1 or 2 (parameter which), stripping off line prefixes. Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) >>> diff = list(diff) # materialize the generated delta into a list >>> print(''.join(restore(diff, 1)), end="") one two three >>> print(''.join(restore(diff, 2)), end="") ore tree emu
python.library.difflib#difflib.restore
class difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True) Optional argument isjunk must be None (the default) or a one-argument function that takes a sequence element and returns true if and only if the element is “junk” and should be ignored. Passing None for isjunk is equivalent to passing lambda x: False; in other words, no elements are ignored. For example, pass: lambda x: x in " \t" if you’re comparing lines as sequences of characters, and don’t want to synch up on blanks or hard tabs. The optional arguments a and b are sequences to be compared; both default to empty strings. The elements of both sequences must be hashable. The optional argument autojunk can be used to disable the automatic junk heuristic. New in version 3.2: The autojunk parameter. SequenceMatcher objects get three data attributes: bjunk is the set of elements of b for which isjunk is True; bpopular is the set of non-junk elements considered popular by the heuristic (if it is not disabled); b2j is a dict mapping the remaining elements of b to a list of positions where they occur. All three are reset whenever b is reset with set_seqs() or set_seq2(). New in version 3.2: The bjunk and bpopular attributes. SequenceMatcher objects have the following methods: set_seqs(a, b) Set the two sequences to be compared. SequenceMatcher computes and caches detailed information about the second sequence, so if you want to compare one sequence against many sequences, use set_seq2() to set the commonly used sequence once and call set_seq1() repeatedly, once for each of the other sequences. set_seq1(a) Set the first sequence to be compared. The second sequence to be compared is not changed. set_seq2(b) Set the second sequence to be compared. The first sequence to be compared is not changed. find_longest_match(alo=0, ahi=None, blo=0, bhi=None) Find longest matching block in a[alo:ahi] and b[blo:bhi]. If isjunk was omitted or None, find_longest_match() returns (i, j, k) such that a[i:i+k] is equal to b[j:j+k], where alo <= i <= i+k <= ahi and blo <= j <= j+k <= bhi. For all (i', j', k') meeting those conditions, the additional conditions k >= k', i <= i', and if i == i', j <= j' are also met. In other words, of all maximal matching blocks, return one that starts earliest in a, and of all those maximal matching blocks that start earliest in a, return the one that starts earliest in b. >>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=0, b=4, size=5) If isjunk was provided, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an interesting match. Here’s the same example as before, but considering blanks to be junk. That prevents ' abcd' from matching the ' abcd' at the tail end of the second sequence directly. Instead only the 'abcd' can match, and matches the leftmost 'abcd' in the second sequence: >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=1, b=0, size=4) If no blocks match, this returns (alo, blo, 0). This method returns a named tuple Match(a, b, size). Changed in version 3.9: Added default arguments. get_matching_blocks() Return list of triples describing non-overlapping matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and j. The last triple is a dummy, and has the value (len(a), len(b), 0). It is the only triple with n == 0. If (i, j, n) and (i', j', n') are adjacent triples in the list, and the second is not the last triple in the list, then i+n < i' or j+n < j'; in other words, adjacent triples always describe non-adjacent equal blocks. >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s.get_matching_blocks() [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] get_opcodes() Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 equal to the i2 from the preceding tuple, and, likewise, j1 equal to the previous j2. The tag values are strings, with these meanings: Value Meaning 'replace' a[i1:i2] should be replaced by b[j1:j2]. 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). For example: >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format( ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) delete a[0:1] --> b[0:0] 'q' --> '' equal a[1:3] --> b[0:2] 'ab' --> 'ab' replace a[3:4] --> b[2:3] 'x' --> 'y' equal a[4:6] --> b[3:5] 'cd' --> 'cd' insert a[6:6] --> b[5:6] '' --> 'f' get_grouped_opcodes(n=3) Return a generator of groups with up to n lines of context. Starting with the groups returned by get_opcodes(), this method splits out smaller change clusters and eliminates intervening ranges which have no changes. The groups are returned in the same format as get_opcodes(). ratio() Return a measure of the sequences’ similarity as a float in the range [0, 1]. Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is 1.0 if the sequences are identical, and 0.0 if they have nothing in common. This is expensive to compute if get_matching_blocks() or get_opcodes() hasn’t already been called, in which case you may want to try quick_ratio() or real_quick_ratio() first to get an upper bound. Note Caution: The result of a ratio() call may depend on the order of the arguments. For instance: >>> SequenceMatcher(None, 'tide', 'diet').ratio() 0.25 >>> SequenceMatcher(None, 'diet', 'tide').ratio() 0.5 quick_ratio() Return an upper bound on ratio() relatively quickly. real_quick_ratio() Return an upper bound on ratio() very quickly.
python.library.difflib#difflib.SequenceMatcher
find_longest_match(alo=0, ahi=None, blo=0, bhi=None) Find longest matching block in a[alo:ahi] and b[blo:bhi]. If isjunk was omitted or None, find_longest_match() returns (i, j, k) such that a[i:i+k] is equal to b[j:j+k], where alo <= i <= i+k <= ahi and blo <= j <= j+k <= bhi. For all (i', j', k') meeting those conditions, the additional conditions k >= k', i <= i', and if i == i', j <= j' are also met. In other words, of all maximal matching blocks, return one that starts earliest in a, and of all those maximal matching blocks that start earliest in a, return the one that starts earliest in b. >>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=0, b=4, size=5) If isjunk was provided, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an interesting match. Here’s the same example as before, but considering blanks to be junk. That prevents ' abcd' from matching the ' abcd' at the tail end of the second sequence directly. Instead only the 'abcd' can match, and matches the leftmost 'abcd' in the second sequence: >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=1, b=0, size=4) If no blocks match, this returns (alo, blo, 0). This method returns a named tuple Match(a, b, size). Changed in version 3.9: Added default arguments.
python.library.difflib#difflib.SequenceMatcher.find_longest_match
get_grouped_opcodes(n=3) Return a generator of groups with up to n lines of context. Starting with the groups returned by get_opcodes(), this method splits out smaller change clusters and eliminates intervening ranges which have no changes. The groups are returned in the same format as get_opcodes().
python.library.difflib#difflib.SequenceMatcher.get_grouped_opcodes
get_matching_blocks() Return list of triples describing non-overlapping matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and j. The last triple is a dummy, and has the value (len(a), len(b), 0). It is the only triple with n == 0. If (i, j, n) and (i', j', n') are adjacent triples in the list, and the second is not the last triple in the list, then i+n < i' or j+n < j'; in other words, adjacent triples always describe non-adjacent equal blocks. >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s.get_matching_blocks() [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
python.library.difflib#difflib.SequenceMatcher.get_matching_blocks
get_opcodes() Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 equal to the i2 from the preceding tuple, and, likewise, j1 equal to the previous j2. The tag values are strings, with these meanings: Value Meaning 'replace' a[i1:i2] should be replaced by b[j1:j2]. 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). For example: >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format( ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) delete a[0:1] --> b[0:0] 'q' --> '' equal a[1:3] --> b[0:2] 'ab' --> 'ab' replace a[3:4] --> b[2:3] 'x' --> 'y' equal a[4:6] --> b[3:5] 'cd' --> 'cd' insert a[6:6] --> b[5:6] '' --> 'f'
python.library.difflib#difflib.SequenceMatcher.get_opcodes
quick_ratio() Return an upper bound on ratio() relatively quickly.
python.library.difflib#difflib.SequenceMatcher.quick_ratio
ratio() Return a measure of the sequences’ similarity as a float in the range [0, 1]. Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is 1.0 if the sequences are identical, and 0.0 if they have nothing in common. This is expensive to compute if get_matching_blocks() or get_opcodes() hasn’t already been called, in which case you may want to try quick_ratio() or real_quick_ratio() first to get an upper bound. Note Caution: The result of a ratio() call may depend on the order of the arguments. For instance: >>> SequenceMatcher(None, 'tide', 'diet').ratio() 0.25 >>> SequenceMatcher(None, 'diet', 'tide').ratio() 0.5
python.library.difflib#difflib.SequenceMatcher.ratio
real_quick_ratio() Return an upper bound on ratio() very quickly.
python.library.difflib#difflib.SequenceMatcher.real_quick_ratio
set_seq1(a) Set the first sequence to be compared. The second sequence to be compared is not changed.
python.library.difflib#difflib.SequenceMatcher.set_seq1
set_seq2(b) Set the second sequence to be compared. The first sequence to be compared is not changed.
python.library.difflib#difflib.SequenceMatcher.set_seq2
set_seqs(a, b) Set the two sequences to be compared.
python.library.difflib#difflib.SequenceMatcher.set_seqs
difflib.unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n') Compare a and b (lists of strings); return a delta (a generator generating the delta lines) in unified diff format. Unified diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in an inline style (instead of separate before/after blocks). The number of context lines is set by n which defaults to three. By default, the diff control lines (those with ---, +++, or @@) are created with a trailing newline. This is helpful so that inputs created from io.IOBase.readlines() result in diffs that are suitable for use with io.IOBase.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for fromfile, tofile, fromfiledate, and tofiledate. The modification times are normally expressed in the ISO 8601 format. If not specified, the strings default to blanks. >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py')) --- before.py +++ after.py @@ -1,4 +1,4 @@ -bacon -eggs -ham +python +eggy +hamster guido See A command-line interface to difflib for a more detailed example.
python.library.difflib#difflib.unified_diff
dir([object]) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes. If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__(). The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information: If the object is a module object, the list contains the names of the module’s attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes. The resulting list is sorted alphabetically. For example: >>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter'] Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
python.library.functions#dir
dis — Disassembler for Python bytecode Source code: Lib/dis.py The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter. CPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. No guarantees are made that bytecode will not be added, removed, or changed between versions of Python. Use of this module should not be considered to work across Python VMs or Python releases. Changed in version 3.6: Use 2 bytes for each instruction. Previously the number of bytes varied by instruction. Example: Given the function myfunc(): def myfunc(alist): return len(alist) the following command can be used to display the disassembly of myfunc(): >>> dis.dis(myfunc) 2 0 LOAD_GLOBAL 0 (len) 2 LOAD_FAST 0 (alist) 4 CALL_FUNCTION 1 6 RETURN_VALUE (The “2” is a line number). Bytecode analysis New in version 3.4. The bytecode analysis API allows pieces of Python code to be wrapped in a Bytecode object that provides easy access to details of the compiled code. class dis.Bytecode(x, *, first_line=None, current_offset=None) Analyse the bytecode corresponding to a function, generator, asynchronous generator, coroutine, method, string of source code, or a code object (as returned by compile()). This is a convenience wrapper around many of the functions listed below, most notably get_instructions(), as iterating over a Bytecode instance yields the bytecode operations as Instruction instances. If first_line is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object. If current_offset is not None, it refers to an instruction offset in the disassembled code. Setting this means dis() will display a “current instruction” marker against the specified opcode. classmethod from_traceback(tb) Construct a Bytecode instance from the given traceback, setting current_offset to the instruction responsible for the exception. codeobj The compiled code object. first_line The first source line of the code object (if available) dis() Return a formatted view of the bytecode operations (the same as printed by dis.dis(), but returned as a multi-line string). info() Return a formatted multi-line string with detailed information about the code object, like code_info(). Changed in version 3.7: This can now handle coroutine and asynchronous generator objects. Example: >>> bytecode = dis.Bytecode(myfunc) >>> for instr in bytecode: ... print(instr.opname) ... LOAD_GLOBAL LOAD_FAST CALL_FUNCTION RETURN_VALUE Analysis functions The dis module also defines the following analysis functions that convert the input directly to the desired output. They can be useful if only a single operation is being performed, so the intermediate analysis object isn’t useful: dis.code_info(x) Return a formatted multi-line string with detailed code object information for the supplied function, generator, asynchronous generator, coroutine, method, source code string or code object. Note that the exact contents of code info strings are highly implementation dependent and they may change arbitrarily across Python VMs or Python releases. New in version 3.2. Changed in version 3.7: This can now handle coroutine and asynchronous generator objects. dis.show_code(x, *, file=None) Print detailed code object information for the supplied function, method, source code string or code object to file (or sys.stdout if file is not specified). This is a convenient shorthand for print(code_info(x), file=file), intended for interactive exploration at the interpreter prompt. New in version 3.2. Changed in version 3.4: Added file parameter. dis.dis(x=None, *, file=None, depth=None) Disassemble the x object. x can denote either a module, a class, a method, a function, a generator, an asynchronous generator, a coroutine, a code object, a string of source code or a byte sequence of raw bytecode. For a module, it disassembles all functions. For a class, it disassembles all methods (including class and static methods). For a code object or sequence of raw bytecode, it prints one line per bytecode instruction. It also recursively disassembles nested code objects (the code of comprehensions, generator expressions and nested functions, and the code used for building nested classes). Strings are first compiled to code objects with the compile() built-in function before being disassembled. If no object is provided, this function disassembles the last traceback. The disassembly is written as text to the supplied file argument if provided and to sys.stdout otherwise. The maximal depth of recursion is limited by depth unless it is None. depth=0 means no recursion. Changed in version 3.4: Added file parameter. Changed in version 3.7: Implemented recursive disassembling and added depth parameter. Changed in version 3.7: This can now handle coroutine and asynchronous generator objects. dis.distb(tb=None, *, file=None) Disassemble the top-of-stack function of a traceback, using the last traceback if none was passed. The instruction causing the exception is indicated. The disassembly is written as text to the supplied file argument if provided and to sys.stdout otherwise. Changed in version 3.4: Added file parameter. dis.disassemble(code, lasti=-1, *, file=None) dis.disco(code, lasti=-1, *, file=None) Disassemble a code object, indicating the last instruction if lasti was provided. The output is divided in the following columns: the line number, for the first instruction of each line the current instruction, indicated as -->, a labelled instruction, indicated with >>, the address of the instruction, the operation code name, operation parameters, and interpretation of the parameters in parentheses. The parameter interpretation recognizes local and global variable names, constant values, branch targets, and compare operators. The disassembly is written as text to the supplied file argument if provided and to sys.stdout otherwise. Changed in version 3.4: Added file parameter. dis.get_instructions(x, *, first_line=None) Return an iterator over the instructions in the supplied function, method, source code string or code object. The iterator generates a series of Instruction named tuples giving the details of each operation in the supplied code. If first_line is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object. New in version 3.4. dis.findlinestarts(code) This generator function uses the co_firstlineno and co_lnotab attributes of the code object code to find the offsets which are starts of lines in the source code. They are generated as (offset, lineno) pairs. See Objects/lnotab_notes.txt for the co_lnotab format and how to decode it. Changed in version 3.6: Line numbers can be decreasing. Before, they were always increasing. dis.findlabels(code) Detect all offsets in the raw compiled bytecode string code which are jump targets, and return a list of these offsets. dis.stack_effect(opcode, oparg=None, *, jump=None) Compute the stack effect of opcode with argument oparg. If the code has a jump target and jump is True, stack_effect() will return the stack effect of jumping. If jump is False, it will return the stack effect of not jumping. And if jump is None (default), it will return the maximal stack effect of both cases. New in version 3.4. Changed in version 3.8: Added jump parameter. Python Bytecode Instructions The get_instructions() function and Bytecode class provide details of bytecode instructions as Instruction instances: class dis.Instruction Details for a bytecode operation opcode numeric code for operation, corresponding to the opcode values listed below and the bytecode values in the Opcode collections. opname human readable name for operation arg numeric argument to operation (if any), otherwise None argval resolved arg value (if known), otherwise same as arg argrepr human readable description of operation argument offset start index of operation within bytecode sequence starts_line line started by this opcode (if any), otherwise None is_jump_target True if other code jumps to here, otherwise False New in version 3.4. The Python compiler currently generates the following bytecode instructions. General instructions NOP Do nothing code. Used as a placeholder by the bytecode optimizer. POP_TOP Removes the top-of-stack (TOS) item. ROT_TWO Swaps the two top-most stack items. ROT_THREE Lifts second and third stack item one position up, moves top down to position three. ROT_FOUR Lifts second, third and fourth stack items one position up, moves top down to position four. New in version 3.8. DUP_TOP Duplicates the reference on top of the stack. New in version 3.2. DUP_TOP_TWO Duplicates the two references on top of the stack, leaving them in the same order. New in version 3.2. Unary operations Unary operations take the top of the stack, apply the operation, and push the result back on the stack. UNARY_POSITIVE Implements TOS = +TOS. UNARY_NEGATIVE Implements TOS = -TOS. UNARY_NOT Implements TOS = not TOS. UNARY_INVERT Implements TOS = ~TOS. GET_ITER Implements TOS = iter(TOS). GET_YIELD_FROM_ITER If TOS is a generator iterator or coroutine object it is left as is. Otherwise, implements TOS = iter(TOS). New in version 3.5. Binary operations Binary operations remove the top of the stack (TOS) and the second top-most stack item (TOS1) from the stack. They perform the operation, and put the result back on the stack. BINARY_POWER Implements TOS = TOS1 ** TOS. BINARY_MULTIPLY Implements TOS = TOS1 * TOS. BINARY_MATRIX_MULTIPLY Implements TOS = TOS1 @ TOS. New in version 3.5. BINARY_FLOOR_DIVIDE Implements TOS = TOS1 // TOS. BINARY_TRUE_DIVIDE Implements TOS = TOS1 / TOS. BINARY_MODULO Implements TOS = TOS1 % TOS. BINARY_ADD Implements TOS = TOS1 + TOS. BINARY_SUBTRACT Implements TOS = TOS1 - TOS. BINARY_SUBSCR Implements TOS = TOS1[TOS]. BINARY_LSHIFT Implements TOS = TOS1 << TOS. BINARY_RSHIFT Implements TOS = TOS1 >> TOS. BINARY_AND Implements TOS = TOS1 & TOS. BINARY_XOR Implements TOS = TOS1 ^ TOS. BINARY_OR Implements TOS = TOS1 | TOS. In-place operations In-place operations are like binary operations, in that they remove TOS and TOS1, and push the result back on the stack, but the operation is done in-place when TOS1 supports it, and the resulting TOS may be (but does not have to be) the original TOS1. INPLACE_POWER Implements in-place TOS = TOS1 ** TOS. INPLACE_MULTIPLY Implements in-place TOS = TOS1 * TOS. INPLACE_MATRIX_MULTIPLY Implements in-place TOS = TOS1 @ TOS. New in version 3.5. INPLACE_FLOOR_DIVIDE Implements in-place TOS = TOS1 // TOS. INPLACE_TRUE_DIVIDE Implements in-place TOS = TOS1 / TOS. INPLACE_MODULO Implements in-place TOS = TOS1 % TOS. INPLACE_ADD Implements in-place TOS = TOS1 + TOS. INPLACE_SUBTRACT Implements in-place TOS = TOS1 - TOS. INPLACE_LSHIFT Implements in-place TOS = TOS1 << TOS. INPLACE_RSHIFT Implements in-place TOS = TOS1 >> TOS. INPLACE_AND Implements in-place TOS = TOS1 & TOS. INPLACE_XOR Implements in-place TOS = TOS1 ^ TOS. INPLACE_OR Implements in-place TOS = TOS1 | TOS. STORE_SUBSCR Implements TOS1[TOS] = TOS2. DELETE_SUBSCR Implements del TOS1[TOS]. Coroutine opcodes GET_AWAITABLE Implements TOS = get_awaitable(TOS), where get_awaitable(o) returns o if o is a coroutine object or a generator object with the CO_ITERABLE_COROUTINE flag, or resolves o.__await__. New in version 3.5. GET_AITER Implements TOS = TOS.__aiter__(). New in version 3.5. Changed in version 3.7: Returning awaitable objects from __aiter__ is no longer supported. GET_ANEXT Implements PUSH(get_awaitable(TOS.__anext__())). See GET_AWAITABLE for details about get_awaitable New in version 3.5. END_ASYNC_FOR Terminates an async for loop. Handles an exception raised when awaiting a next item. If TOS is StopAsyncIteration pop 7 values from the stack and restore the exception state using the second three of them. Otherwise re-raise the exception using the three values from the stack. An exception handler block is removed from the block stack. New in version 3.8. BEFORE_ASYNC_WITH Resolves __aenter__ and __aexit__ from the object on top of the stack. Pushes __aexit__ and result of __aenter__() to the stack. New in version 3.5. SETUP_ASYNC_WITH Creates a new frame object. New in version 3.5. Miscellaneous opcodes PRINT_EXPR Implements the expression statement for the interactive mode. TOS is removed from the stack and printed. In non-interactive mode, an expression statement is terminated with POP_TOP. SET_ADD(i) Calls set.add(TOS1[-i], TOS). Used to implement set comprehensions. LIST_APPEND(i) Calls list.append(TOS1[-i], TOS). Used to implement list comprehensions. MAP_ADD(i) Calls dict.__setitem__(TOS1[-i], TOS1, TOS). Used to implement dict comprehensions. New in version 3.1. Changed in version 3.8: Map value is TOS and map key is TOS1. Before, those were reversed. For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while the added value or key/value pair is popped off, the container object remains on the stack so that it is available for further iterations of the loop. RETURN_VALUE Returns with TOS to the caller of the function. YIELD_VALUE Pops TOS and yields it from a generator. YIELD_FROM Pops TOS and delegates to it as a subiterator from a generator. New in version 3.3. SETUP_ANNOTATIONS Checks whether __annotations__ is defined in locals(), if not it is set up to an empty dict. This opcode is only emitted if a class or module body contains variable annotations statically. New in version 3.6. IMPORT_STAR Loads all symbols not starting with '_' directly from the module TOS to the local namespace. The module is popped after loading all names. This opcode implements from module import *. POP_BLOCK Removes one block from the block stack. Per frame, there is a stack of blocks, denoting try statements, and such. POP_EXCEPT Removes one block from the block stack. The popped block must be an exception handler block, as implicitly created when entering an except handler. In addition to popping extraneous values from the frame stack, the last three popped values are used to restore the exception state. RERAISE Re-raises the exception currently on top of the stack. New in version 3.9. WITH_EXCEPT_START Calls the function in position 7 on the stack with the top three items on the stack as arguments. Used to implement the call context_manager.__exit__(*exc_info()) when an exception has occurred in a with statement. New in version 3.9. LOAD_ASSERTION_ERROR Pushes AssertionError onto the stack. Used by the assert statement. New in version 3.9. LOAD_BUILD_CLASS Pushes builtins.__build_class__() onto the stack. It is later called by CALL_FUNCTION to construct a class. SETUP_WITH(delta) This opcode performs several operations before a with block starts. First, it loads __exit__() from the context manager and pushes it onto the stack for later use by WITH_CLEANUP_START. Then, __enter__() is called, and a finally block pointing to delta is pushed. Finally, the result of calling the __enter__() method is pushed onto the stack. The next opcode will either ignore it (POP_TOP), or store it in (a) variable(s) (STORE_FAST, STORE_NAME, or UNPACK_SEQUENCE). New in version 3.2. All of the following opcodes use their arguments. STORE_NAME(namei) Implements name = TOS. namei is the index of name in the attribute co_names of the code object. The compiler tries to use STORE_FAST or STORE_GLOBAL if possible. DELETE_NAME(namei) Implements del name, where namei is the index into co_names attribute of the code object. UNPACK_SEQUENCE(count) Unpacks TOS into count individual values, which are put onto the stack right-to-left. UNPACK_EX(counts) Implements assignment with a starred target: Unpacks an iterable in TOS into individual values, where the total number of values can be smaller than the number of items in the iterable: one of the new values will be a list of all leftover items. The low byte of counts is the number of values before the list value, the high byte of counts the number of values after it. The resulting values are put onto the stack right-to-left. STORE_ATTR(namei) Implements TOS.name = TOS1, where namei is the index of name in co_names. DELETE_ATTR(namei) Implements del TOS.name, using namei as index into co_names. STORE_GLOBAL(namei) Works as STORE_NAME, but stores the name as a global. DELETE_GLOBAL(namei) Works as DELETE_NAME, but deletes a global name. LOAD_CONST(consti) Pushes co_consts[consti] onto the stack. LOAD_NAME(namei) Pushes the value associated with co_names[namei] onto the stack. BUILD_TUPLE(count) Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack. BUILD_LIST(count) Works as BUILD_TUPLE, but creates a list. BUILD_SET(count) Works as BUILD_TUPLE, but creates a set. BUILD_MAP(count) Pushes a new dictionary object onto the stack. Pops 2 * count items so that the dictionary holds count entries: {..., TOS3: TOS2, TOS1: TOS}. Changed in version 3.5: The dictionary is created from stack items instead of creating an empty dictionary pre-sized to hold count items. BUILD_CONST_KEY_MAP(count) The version of BUILD_MAP specialized for constant keys. Pops the top element on the stack which contains a tuple of keys, then starting from TOS1, pops count values to form values in the built dictionary. New in version 3.6. BUILD_STRING(count) Concatenates count strings from the stack and pushes the resulting string onto the stack. New in version 3.6. LIST_TO_TUPLE Pops a list from the stack and pushes a tuple containing the same values. New in version 3.9. LIST_EXTEND(i) Calls list.extend(TOS1[-i], TOS). Used to build lists. New in version 3.9. SET_UPDATE(i) Calls set.update(TOS1[-i], TOS). Used to build sets. New in version 3.9. DICT_UPDATE(i) Calls dict.update(TOS1[-i], TOS). Used to build dicts. New in version 3.9. DICT_MERGE Like DICT_UPDATE but raises an exception for duplicate keys. New in version 3.9. LOAD_ATTR(namei) Replaces TOS with getattr(TOS, co_names[namei]). COMPARE_OP(opname) Performs a Boolean operation. The operation name can be found in cmp_op[opname]. IS_OP(invert) Performs is comparison, or is not if invert is 1. New in version 3.9. CONTAINS_OP(invert) Performs in comparison, or not in if invert is 1. New in version 3.9. IMPORT_NAME(namei) Imports the module co_names[namei]. TOS and TOS1 are popped and provide the fromlist and level arguments of __import__(). The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent STORE_FAST instruction modifies the namespace. IMPORT_FROM(namei) Loads the attribute co_names[namei] from the module found in TOS. The resulting object is pushed onto the stack, to be subsequently stored by a STORE_FAST instruction. JUMP_FORWARD(delta) Increments bytecode counter by delta. POP_JUMP_IF_TRUE(target) If TOS is true, sets the bytecode counter to target. TOS is popped. New in version 3.1. POP_JUMP_IF_FALSE(target) If TOS is false, sets the bytecode counter to target. TOS is popped. New in version 3.1. JUMP_IF_NOT_EXC_MATCH(target) Tests whether the second value on the stack is an exception matching TOS, and jumps if it is not. Pops two values from the stack. New in version 3.9. JUMP_IF_TRUE_OR_POP(target) If TOS is true, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is false), TOS is popped. New in version 3.1. JUMP_IF_FALSE_OR_POP(target) If TOS is false, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is true), TOS is popped. New in version 3.1. JUMP_ABSOLUTE(target) Set bytecode counter to target. FOR_ITER(delta) TOS is an iterator. Call its __next__() method. If this yields a new value, push it on the stack (leaving the iterator below it). If the iterator indicates it is exhausted, TOS is popped, and the byte code counter is incremented by delta. LOAD_GLOBAL(namei) Loads the global named co_names[namei] onto the stack. SETUP_FINALLY(delta) Pushes a try block from a try-finally or try-except clause onto the block stack. delta points to the finally block or the first except block. LOAD_FAST(var_num) Pushes a reference to the local co_varnames[var_num] onto the stack. STORE_FAST(var_num) Stores TOS into the local co_varnames[var_num]. DELETE_FAST(var_num) Deletes local co_varnames[var_num]. LOAD_CLOSURE(i) Pushes a reference to the cell contained in slot i of the cell and free variable storage. The name of the variable is co_cellvars[i] if i is less than the length of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)]. LOAD_DEREF(i) Loads the cell contained in slot i of the cell and free variable storage. Pushes a reference to the object the cell contains on the stack. LOAD_CLASSDEREF(i) Much like LOAD_DEREF but first checks the locals dictionary before consulting the cell. This is used for loading free variables in class bodies. New in version 3.4. STORE_DEREF(i) Stores TOS into the cell contained in slot i of the cell and free variable storage. DELETE_DEREF(i) Empties the cell contained in slot i of the cell and free variable storage. Used by the del statement. New in version 3.2. RAISE_VARARGS(argc) Raises an exception using one of the 3 forms of the raise statement, depending on the value of argc: 0: raise (re-raise previous exception) 1: raise TOS (raise exception instance or type at TOS) 2: raise TOS1 from TOS (raise exception instance or type at TOS1 with __cause__ set to TOS) CALL_FUNCTION(argc) Calls a callable object with positional arguments. argc indicates the number of positional arguments. The top of the stack contains positional arguments, with the right-most argument on top. Below the arguments is a callable object to call. CALL_FUNCTION pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object. Changed in version 3.6: This opcode is used only for calls with positional arguments. CALL_FUNCTION_KW(argc) Calls a callable object with positional (if any) and keyword arguments. argc indicates the total number of positional and keyword arguments. The top element on the stack contains a tuple with the names of the keyword arguments, which must be strings. Below that are the values for the keyword arguments, in the order corresponding to the tuple. Below that are positional arguments, with the right-most parameter on top. Below the arguments is a callable object to call. CALL_FUNCTION_KW pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object. Changed in version 3.6: Keyword arguments are packed in a tuple instead of a dictionary, argc indicates the total number of arguments. CALL_FUNCTION_EX(flags) Calls a callable object with variable set of positional and keyword arguments. If the lowest bit of flags is set, the top of the stack contains a mapping object containing additional keyword arguments. Before the callable is called, the mapping object and iterable object are each “unpacked” and their contents passed in as keyword and positional arguments respectively. CALL_FUNCTION_EX pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object. New in version 3.6. LOAD_METHOD(namei) Loads a method named co_names[namei] from the TOS object. TOS is popped. This bytecode distinguishes two cases: if TOS has a method with the correct name, the bytecode pushes the unbound method and TOS. TOS will be used as the first argument (self) by CALL_METHOD when calling the unbound method. Otherwise, NULL and the object return by the attribute lookup are pushed. New in version 3.7. CALL_METHOD(argc) Calls a method. argc is the number of positional arguments. Keyword arguments are not supported. This opcode is designed to be used with LOAD_METHOD. Positional arguments are on top of the stack. Below them, the two items described in LOAD_METHOD are on the stack (either self and an unbound method object or NULL and an arbitrary callable). All of them are popped and the return value is pushed. New in version 3.7. MAKE_FUNCTION(flags) Pushes a new function object on the stack. From bottom to top, the consumed stack must consist of values if the argument carries a specified flag value 0x01 a tuple of default values for positional-only and positional-or-keyword parameters in positional order 0x02 a dictionary of keyword-only parameters’ default values 0x04 an annotation dictionary 0x08 a tuple containing cells for free variables, making a closure the code associated with the function (at TOS1) the qualified name of the function (at TOS) BUILD_SLICE(argc) Pushes a slice object on the stack. argc must be 2 or 3. If it is 2, slice(TOS1, TOS) is pushed; if it is 3, slice(TOS2, TOS1, TOS) is pushed. See the slice() built-in function for more information. EXTENDED_ARG(ext) Prefixes any opcode which has an argument too big to fit into the default one byte. ext holds an additional byte which act as higher bits in the argument. For each opcode, at most three prefixal EXTENDED_ARG are allowed, forming an argument from two-byte to four-byte. FORMAT_VALUE(flags) Used for implementing formatted literal strings (f-strings). Pops an optional fmt_spec from the stack, then a required value. flags is interpreted as follows: (flags & 0x03) == 0x00: value is formatted as-is. (flags & 0x03) == 0x01: call str() on value before formatting it. (flags & 0x03) == 0x02: call repr() on value before formatting it. (flags & 0x03) == 0x03: call ascii() on value before formatting it. (flags & 0x04) == 0x04: pop fmt_spec from the stack and use it, else use an empty fmt_spec. Formatting is performed using PyObject_Format(). The result is pushed on the stack. New in version 3.6. HAVE_ARGUMENT This is not really an opcode. It identifies the dividing line between opcodes which don’t use their argument and those that do (< HAVE_ARGUMENT and >= HAVE_ARGUMENT, respectively). Changed in version 3.6: Now every instruction has an argument, but opcodes < HAVE_ARGUMENT ignore it. Before, only opcodes >= HAVE_ARGUMENT had an argument. Opcode collections These collections are provided for automatic introspection of bytecode instructions: dis.opname Sequence of operation names, indexable using the bytecode. dis.opmap Dictionary mapping operation names to bytecodes. dis.cmp_op Sequence of all compare operation names. dis.hasconst Sequence of bytecodes that access a constant. dis.hasfree Sequence of bytecodes that access a free variable (note that ‘free’ in this context refers to names in the current scope that are referenced by inner scopes or names in outer scopes that are referenced from this scope. It does not include references to global or builtin scopes). dis.hasname Sequence of bytecodes that access an attribute by name. dis.hasjrel Sequence of bytecodes that have a relative jump target. dis.hasjabs Sequence of bytecodes that have an absolute jump target. dis.haslocal Sequence of bytecodes that access a local variable. dis.hascompare Sequence of bytecodes of Boolean operations.
python.library.dis
class dis.Bytecode(x, *, first_line=None, current_offset=None) Analyse the bytecode corresponding to a function, generator, asynchronous generator, coroutine, method, string of source code, or a code object (as returned by compile()). This is a convenience wrapper around many of the functions listed below, most notably get_instructions(), as iterating over a Bytecode instance yields the bytecode operations as Instruction instances. If first_line is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object. If current_offset is not None, it refers to an instruction offset in the disassembled code. Setting this means dis() will display a “current instruction” marker against the specified opcode. classmethod from_traceback(tb) Construct a Bytecode instance from the given traceback, setting current_offset to the instruction responsible for the exception. codeobj The compiled code object. first_line The first source line of the code object (if available) dis() Return a formatted view of the bytecode operations (the same as printed by dis.dis(), but returned as a multi-line string). info() Return a formatted multi-line string with detailed information about the code object, like code_info(). Changed in version 3.7: This can now handle coroutine and asynchronous generator objects.
python.library.dis#dis.Bytecode
codeobj The compiled code object.
python.library.dis#dis.Bytecode.codeobj
dis() Return a formatted view of the bytecode operations (the same as printed by dis.dis(), but returned as a multi-line string).
python.library.dis#dis.Bytecode.dis
first_line The first source line of the code object (if available)
python.library.dis#dis.Bytecode.first_line
classmethod from_traceback(tb) Construct a Bytecode instance from the given traceback, setting current_offset to the instruction responsible for the exception.
python.library.dis#dis.Bytecode.from_traceback
info() Return a formatted multi-line string with detailed information about the code object, like code_info().
python.library.dis#dis.Bytecode.info