curses.ungetmouse(id, x, y, z, bstate)
Push a KEY_MOUSE event onto the input queue, associating the given state data with it.


curses.unget_wch(ch)
Push ch so the next get_wch() will return it.  Note Only one ch can be pushed before get_wch() is called.   New in version 3.3.


curses.update_lines_cols()
Update LINES and COLS. Useful for detecting manual screen resize.  New in version 3.5.


curses.use_default_colors()
Allow use of default values for colors on terminals supporting this feature. Use this to support transparency in your application. The default color is assigned to the color number -1. After calling this function, init_pair(x,
curses.COLOR_RED, -1) initializes, for instance, color pair x to a red foreground color on the default background.


curses.use_env(flag)
If used, this function should be called before initscr() or newterm are called. When flag is False, the values of lines and columns specified in the terminfo database will be used, even if environment variables LINES and COLUMNS (used by default) are set, or if curses is running in a window (in which case default behavior would be to use the window size if LINES and COLUMNS are not set).


curses.version
A bytes object representing the current version of the module. Also available as __version__.


window.addch(ch[, attr])
window.addch(y, x, ch[, attr])
Paint character ch at (y, x) with attributes attr, overwriting any character previously painted at that location. By default, the character position and attributes are the current settings for the window object.  Note Writing outside the window, subwindow, or pad raises a curses.error. Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the character is printed.


window.addnstr(str, n[, attr])
window.addnstr(y, x, str, n[, attr])
Paint at most n characters of the character string str at (y, x) with attributes attr, overwriting anything previously on the display.


window.addstr(str[, attr])
window.addstr(y, x, str[, attr])
Paint the character string str at (y, x) with attributes attr, overwriting anything previously on the display.  Note  Writing outside the window, subwindow, or pad raises curses.error. Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the string is printed. A bug in ncurses, the backend for this Python module, can cause SegFaults when resizing windows. This is fixed in ncurses-6.1-20190511. If you are stuck with an earlier ncurses, you can avoid triggering this if you do not call addstr() with a str that has embedded newlines. Instead, call addstr() separately for each line.


window.attroff(attr)
Remove attribute attr from the “background” set applied to all writes to the current window.


window.attron(attr)
Add attribute attr from the “background” set applied to all writes to the current window.


window.attrset(attr)
Set the “background” set of attributes to attr. This set is initially 0 (no attributes).


window.bkgd(ch[, attr])
Set the background property of the window to the character ch, with attributes attr. The change is then applied to every character position in that window:  The attribute of every character in the window is changed to the new background attribute. Wherever the former background character appears, it is changed to the new background character.


window.bkgdset(ch[, attr])
Set the window’s background. A window’s background consists of a character and any combination of attributes. The attribute part of the background is combined (OR’ed) with all non-blank characters that are written into the window. Both the character and attribute parts of the background are combined with the blank characters. The background becomes a property of the character and moves with the character through any scrolling and insert/delete line/character operations.


window.border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])
Draw a border around the edges of the window. Each parameter specifies the character to use for a specific part of the border; see the table below for more details.  Note A 0 value for any parameter will cause the default character to be used for that parameter. Keyword parameters can not be used. The defaults are listed in this table:
Parameter Description Default value
ls Left side ACS_VLINE
rs Right side ACS_VLINE
ts Top ACS_HLINE
bs Bottom ACS_HLINE
tl Upper-left corner ACS_ULCORNER
tr Upper-right corner ACS_URCORNER
bl Bottom-left corner ACS_LLCORNER
br Bottom-right corner ACS_LRCORNER


window.box([vertch, horch])
Similar to border(), but both ls and rs are vertch and both ts and bs are horch. The default corner characters are always used by this function.


window.chgat(attr)
window.chgat(num, attr)
window.chgat(y, x, attr)
window.chgat(y, x, num, attr)
Set the attributes of num characters at the current cursor position, or at position (y, x) if supplied. If num is not given or is -1, the attribute will be set on all the characters to the end of the line. This function moves cursor to position (y, x) if supplied. The changed line will be touched using the touchline() method so that the contents will be redisplayed by the next window refresh.


window.clear()
Like erase(), but also cause the whole window to be repainted upon next call to refresh().


window.clearok(flag)
If flag is True, the next call to refresh() will clear the window completely.


window.clrtobot()
Erase from cursor to the end of the window: all lines below the cursor are deleted, and then the equivalent of clrtoeol() is performed.


window.clrtoeol()
Erase from cursor to the end of the line.


window.cursyncup()
Update the current cursor position of all the ancestors of the window to reflect the current cursor position of the window.


window.delch([y, x])
Delete any character at (y, x).


window.deleteln()
Delete the line under the cursor. All following lines are moved up by one line.


window.derwin(begin_y, begin_x)
window.derwin(nlines, ncols, begin_y, begin_x)
An abbreviation for “derive window”, derwin() is the same as calling subwin(), except that begin_y and begin_x are relative to the origin of the window, rather than relative to the entire screen. Return a window object for the derived window.


window.echochar(ch[, attr])
Add character ch with attribute attr, and immediately call refresh() on the window.


window.enclose(y, x)
Test whether the given pair of screen-relative character-cell coordinates are enclosed by the given window, returning True or False. It is useful for determining what subset of the screen windows enclose the location of a mouse event.


window.encoding
Encoding used to encode method arguments (Unicode strings and characters). The encoding attribute is inherited from the parent window when a subwindow is created, for example with window.subwin(). By default, the locale encoding is used (see locale.getpreferredencoding()).  New in version 3.3.


window.getbegyx()
Return a tuple (y, x) of co-ordinates of upper-left corner.


window.getbkgd()
Return the given window’s current background character/attribute pair.


window.getch([y, x])
Get a character. Note that the integer returned does not have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return -1 if there is no input, otherwise wait until a key is pressed.


window.getkey([y, x])
Get a character, returning a string instead of an integer, as getch() does. Function keys, keypad keys and other special keys return a multibyte string containing the key name. In no-delay mode, raise an exception if there is no input.


window.getmaxyx()
Return a tuple (y, x) of the height and width of the window.


window.getparyx()
Return the beginning coordinates of this window relative to its parent window as a tuple (y, x). Return (-1, -1) if this window has no parent.


window.getstr()
window.getstr(n)
window.getstr(y, x)
window.getstr(y, x, n)
Read a bytes object from the user, with primitive line editing capacity.


window.getyx()
Return a tuple (y, x) of current cursor position relative to the window’s upper-left corner.


window.get_wch([y, x])
Get a wide character. Return a character for most keys, or an integer for function keys, keypad keys, and other special keys. In no-delay mode, raise an exception if there is no input.  New in version 3.3.


window.hline(ch, n)
window.hline(y, x, ch, n)
Display a horizontal line starting at (y, x) with length n consisting of the character ch.


window.idcok(flag)
If flag is False, curses no longer considers using the hardware insert/delete character feature of the terminal; if flag is True, use of character insertion and deletion is enabled. When curses is first initialized, use of character insert/delete is enabled by default.


window.idlok(flag)
If flag is True, curses will try and use hardware line editing facilities. Otherwise, line insertion/deletion are disabled.


window.immedok(flag)
If flag is True, any change in the window image automatically causes the window to be refreshed; you no longer have to call refresh() yourself. However, it may degrade performance considerably, due to repeated calls to wrefresh. This option is disabled by default.


window.inch([y, x])
Return the character at the given position in the window. The bottom 8 bits are the character proper, and upper bits are the attributes.


window.insch(ch[, attr])
window.insch(y, x, ch[, attr])
Paint character ch at (y, x) with attributes attr, moving the line from position x right by one character.


window.insdelln(nlines)
Insert nlines lines into the specified window above the current line. The nlines bottom lines are lost. For negative nlines, delete nlines lines starting with the one under the cursor, and move the remaining lines up. The bottom nlines lines are cleared. The current cursor position remains the same.


window.insertln()
Insert a blank line under the cursor. All following lines are moved down by one line.


window.insnstr(str, n[, attr])
window.insnstr(y, x, str, n[, attr])
Insert a character string (as many characters as will fit on the line) before the character under the cursor, up to n characters. If n is zero or negative, the entire string is inserted. All characters to the right of the cursor are shifted right, with the rightmost characters on the line being lost. The cursor position does not change (after moving to y, x, if specified).


window.insstr(str[, attr])
window.insstr(y, x, str[, attr])
Insert a character string (as many characters as will fit on the line) before the character under the cursor. All characters to the right of the cursor are shifted right, with the rightmost characters on the line being lost. The cursor position does not change (after moving to y, x, if specified).


window.instr([n])
window.instr(y, x[, n])
Return a bytes object of characters, extracted from the window starting at the current cursor position, or at y, x if specified. Attributes are stripped from the characters. If n is specified, instr() returns a string at most n characters long (exclusive of the trailing NUL).


window.is_linetouched(line)
Return True if the specified line was modified since the last call to refresh(); otherwise return False. Raise a curses.error exception if line is not valid for the given window.


window.is_wintouched()
Return True if the specified window was modified since the last call to refresh(); otherwise return False.


window.keypad(flag)
If flag is True, escape sequences generated by some keys (keypad, function keys) will be interpreted by curses. If flag is False, escape sequences will be left as is in the input stream.


window.leaveok(flag)
If flag is True, cursor is left where it is on update, instead of being at “cursor position.” This reduces cursor movement where possible. If possible the cursor will be made invisible. If flag is False, cursor will always be at “cursor position” after an update.


window.move(new_y, new_x)
Move cursor to (new_y, new_x).


window.mvderwin(y, x)
Move the window inside its parent window. The screen-relative parameters of the window are not changed. This routine is used to display different parts of the parent window at the same physical position on the screen.


window.mvwin(new_y, new_x)
Move the window so its upper-left corner is at (new_y, new_x).


window.nodelay(flag)
If flag is True, getch() will be non-blocking.


window.notimeout(flag)
If flag is True, escape sequences will not be timed out. If flag is False, after a few milliseconds, an escape sequence will not be interpreted, and will be left in the input stream as is.


window.noutrefresh()
Mark for refresh but wait. This function updates the data structure representing the desired state of the window, but does not force an update of the physical screen. To accomplish that, call doupdate().


window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])
Overlay the window on top of destwin. The windows need not be the same size, only the overlapping region is copied. This copy is non-destructive, which means that the current background character does not overwrite the old contents of destwin. To get fine-grained control over the copied region, the second form of overlay() can be used. sminrow and smincol are the upper-left coordinates of the source window, and the other variables mark a rectangle in the destination window.


window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])
Overwrite the window on top of destwin. The windows need not be the same size, in which case only the overlapping region is copied. This copy is destructive, which means that the current background character overwrites the old contents of destwin. To get fine-grained control over the copied region, the second form of overwrite() can be used. sminrow and smincol are the upper-left coordinates of the source window, the other variables mark a rectangle in the destination window.


window.putwin(file)
Write all data associated with the window into the provided file object. This information can be later retrieved using the getwin() function.


window.redrawln(beg, num)
Indicate that the num screen lines, starting at line beg, are corrupted and should be completely redrawn on the next refresh() call.


window.redrawwin()
Touch the entire window, causing it to be completely redrawn on the next refresh() call.


window.refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])
Update the display immediately (sync actual screen with previous drawing/deleting methods). The 6 optional arguments can only be specified when the window is a pad created with newpad(). The additional parameters are needed to indicate what part of the pad and screen are involved. pminrow and pmincol specify the upper left-hand corner of the rectangle to be displayed in the pad. sminrow, smincol, smaxrow, and smaxcol specify the edges of the rectangle to be displayed on the screen. The lower right-hand corner of the rectangle to be displayed in the pad is calculated from the screen coordinates, since the rectangles must be the same size. Both rectangles must be entirely contained within their respective structures. Negative values of pminrow, pmincol, sminrow, or smincol are treated as if they were zero.


window.resize(nlines, ncols)
Reallocate storage for a curses window to adjust its dimensions to the specified values. If either dimension is larger than the current values, the window’s data is filled with blanks that have the current background rendition (as set by bkgdset()) merged into them.


window.scroll([lines=1])
Scroll the screen or scrolling region upward by lines lines.


window.scrollok(flag)
Control what happens when the cursor of a window is moved off the edge of the window or scrolling region, either as a result of a newline action on the bottom line, or typing the last character of the last line. If flag is False, the cursor is left on the bottom line. If flag is True, the window is scrolled up one line. Note that in order to get the physical scrolling effect on the terminal, it is also necessary to call idlok().


window.setscrreg(top, bottom)
Set the scrolling region from line top to line bottom. All scrolling actions will take place in this region.


window.standend()
Turn off the standout attribute. On some terminals this has the side effect of turning off all attributes.


window.standout()
Turn on attribute A_STANDOUT.


window.subpad(begin_y, begin_x)
window.subpad(nlines, ncols, begin_y, begin_x)
Return a sub-window, whose upper-left corner is at (begin_y, begin_x), and whose width/height is ncols/nlines.


window.subwin(begin_y, begin_x)
window.subwin(nlines, ncols, begin_y, begin_x)
Return a sub-window, whose upper-left corner is at (begin_y, begin_x), and whose width/height is ncols/nlines. By default, the sub-window will extend from the specified position to the lower right corner of the window.


window.syncdown()
Touch each location in the window that has been touched in any of its ancestor windows. This routine is called by refresh(), so it should almost never be necessary to call it manually.


window.syncok(flag)
If flag is True, then syncup() is called automatically whenever there is a change in the window.


window.syncup()
Touch all locations in ancestors of the window that have been changed in the window.


window.timeout(delay)
Set blocking or non-blocking read behavior for the window. If delay is negative, blocking read is used (which will wait indefinitely for input). If delay is zero, then non-blocking read is used, and getch() will return -1 if no input is waiting. If delay is positive, then getch() will block for delay milliseconds, and return -1 if there is still no input at the end of that time.


window.touchline(start, count[, changed])
Pretend count lines have been changed, starting with line start. If changed is supplied, it specifies whether the affected lines are marked as having been changed (changed=True) or unchanged (changed=False).


window.touchwin()
Pretend the whole window has been changed, for purposes of drawing optimizations.


window.untouchwin()
Mark all lines in the window as unchanged since the last call to refresh().


window.vline(ch, n)
window.vline(y, x, ch, n)
Display a vertical line starting at (y, x) with length n consisting of the character ch.


curses.wrapper(func, /, *args, **kwargs)
Initialize curses and call another callable object, func, which should be the rest of your curses-using application. If the application raises an exception, this function will restore the terminal to a sane state before re-raising the exception and generating a traceback. The callable object func is then passed the main window ‘stdscr’ as its first argument, followed by any other arguments passed to wrapper(). Before calling func, wrapper() turns on cbreak mode, turns off echo, enables the terminal keypad, and initializes colors if the terminal has color support. On exit (whether normally or by exception) it restores cooked mode, turns on echo, and disables the terminal keypad.


dataclasses — Data Classes Source code: Lib/dataclasses.py This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557. The member variables to use in these generated methods are defined using PEP 526 type annotations. For example this code: from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand
 Will add, among other things, a __init__() that looks like: def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand
 Note that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.  New in version 3.7.  Module-level decorators, classes, and functions
@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
This function is a decorator that is used to add generated special methods to classes, as described below. The dataclass() decorator examines the class to find fields. A field is defined as class variable that has a type annotation. With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation. The order of the fields in all of the generated methods is the order in which they appear in the class definition. The dataclass() decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist on the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that is called on; no new class is created. If dataclass() is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of dataclass() are equivalent: @dataclass
class C:
    ...

@dataclass()
class C:
    ...

@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class C:
   ...
 The parameters to dataclass() are:
init: If true (the default), a __init__() method will be generated. If the class already defines __init__(), this parameter is ignored.
repr: If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10). If the class already defines __repr__(), this parameter is ignored.
eq: If true (the default), an __eq__() method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If the class already defines __eq__(), this parameter is ignored.
order: If true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised. If the class already defines any of __lt__(), __le__(), __gt__(), or __ge__(), then TypeError is raised.
unsafe_hash: If False (the default), a __hash__() method is generated according to how eq and frozen are set. __hash__() is used by built-in hash(), and when objects are added to hashed collections such as dictionaries and sets. Having a __hash__() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of __eq__(), and the values of the eq and frozen flags in the dataclass() decorator. By default, dataclass() will not implicitly add a __hash__() method unless it is safe to do so. Neither will it add or change an existing explicitly defined __hash__() method. Setting the class attribute __hash__ = None has a specific meaning to Python, as described in the __hash__() documentation. If __hash__() is not explicitly defined, or if it is set to None, then dataclass() may add an implicit __hash__() method. Although not recommended, you can force dataclass() to create a __hash__() method with unsafe_hash=True. This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully. Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True; this will result in a TypeError. If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None, marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object, this means it will fall back to id-based hashing).
frozen: If true (the default is False), assigning to fields will generate an exception. This emulates read-only frozen instances. If __setattr__() or __delattr__() is defined in the class, then TypeError is raised. See the discussion below.  fields may optionally specify a default value, using normal Python syntax: @dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'
 In this example, both a and b will be included in the added __init__() method, which will be defined as: def __init__(self, a: int, b: int = 0):
 TypeError will be raised if a field without a default value follows a field with a default value. This is true either when this occurs in a single class, or as a result of class inheritance.

dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function. For example: @dataclass
class C:
    mylist: list[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]
 As shown above, the MISSING value is a sentinel object used to detect if the default and default_factory parameters are provided. This sentinel is used because None is a valid value for default. No code should directly use the MISSING value. The parameters to field() are:
default: If provided, this will be the default value for this field. This is needed because the field() call itself replaces the normal position of the default value.
default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory.
init: If true (the default), this field is included as a parameter to the generated __init__() method.
repr: If true (the default), this field is included in the string returned by the generated __repr__() method.
compare: If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.).
hash: This can be a bool or None. If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare: this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged. One possible reason to set hash=False but compare=True would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.
metadata: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.  If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified default value. If no default is provided, then the class attribute will be deleted. The intent is that after the dataclass() decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after: @dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20
 The class attribute C.z will be 10, the class attribute C.t will be 20, and the class attributes C.x and C.y will not be set.

class dataclasses.Field
Field objects describe each defined field. These objects are created internally, and are returned by the fields() module-level method (see below). Users should never instantiate a Field object directly. Its documented attributes are:
name: The name of the field.
type: The type of the field.
default, default_factory, init, repr, hash, compare, and metadata have the identical meaning and values as they do in the field() declaration.  Other attributes may exist, but they are private and must not be inspected or relied on.

dataclasses.fields(class_or_instance)
Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises TypeError if not passed a dataclass or instance of one. Does not return pseudo-fields which are ClassVar or InitVar.

dataclasses.asdict(instance, *, dict_factory=dict)
Converts the dataclass instance to a dict (by using the factory function dict_factory). Each dataclass is converted to a dict of its fields, as name: value pairs. dataclasses, dicts, lists, and tuples are recursed into. For example: @dataclass
class Point:
     x: int
     y: int

@dataclass
class C:
     mylist: list[Point]

p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}

c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
 Raises TypeError if instance is not a dataclass instance.

dataclasses.astuple(instance, *, tuple_factory=tuple)
Converts the dataclass instance to a tuple (by using the factory function tuple_factory). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, lists, and tuples are recursed into. Continuing from the previous example: assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)
 Raises TypeError if instance is not a dataclass instance.

dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
Creates a new dataclass with name cls_name, fields as defined in fields, base classes as given in bases, and initialized with a namespace as given in namespace. fields is an iterable whose elements are each either name, (name, type), or (name, type, Field). If just name is supplied, typing.Any is used for type. The values of init, repr, eq, order, unsafe_hash, and frozen have the same meaning as they do in dataclass(). This function is not strictly required, because any Python mechanism for creating a new class with __annotations__ can then apply the dataclass() function to convert that class to a dataclass. This function is provided as a convenience. For example: C = make_dataclass('C',
                   [('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace={'add_one': lambda self: self.x + 1})
 Is equivalent to: @dataclass
class C:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1

dataclasses.replace(instance, /, **changes)
Creates a new object of the same type of instance, replacing fields with values from changes. If instance is not a Data Class, raises TypeError. If values in changes do not specify fields, raises TypeError. The newly returned object is created by calling the __init__() method of the dataclass. This ensures that __post_init__(), if present, is also called. Init-only variables without default values, if any exist, must be specified on the call to replace() so that they can be passed to __init__() and __post_init__(). It is an error for changes to contain any fields that are defined as having init=False. A ValueError will be raised in this case. Be forewarned about how init=False fields work during a call to replace(). They are not copied from the source object, but rather are initialized in __post_init__(), if they’re initialized at all. It is expected that init=False fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom replace() (or similarly named) method which handles instance copying.

dataclasses.is_dataclass(class_or_instance)
Return True if its parameter is a dataclass or an instance of one, otherwise return False. If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for not
isinstance(obj, type): def is_dataclass_instance(obj):
    return is_dataclass(obj) and not isinstance(obj, type)

 Post-init processing The generated __init__() code will call a method named __post_init__(), if __post_init__() is defined on the class. It will normally be called as self.__post_init__(). However, if any InitVar fields are defined, they will also be passed to __post_init__() in the order they were defined in the class. If no __init__() method is generated, then __post_init__() will not automatically be called. Among other uses, this allows for initializing field values that depend on one or more other fields. For example: @dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self):
        self.c = self.a + self.b
 See the section below on init-only variables for ways to pass parameters to __post_init__(). Also see the warning about how replace() handles init=False fields. Class variables One of two places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function. Init-only variables The other place where dataclass() inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type dataclasses.InitVar. If a field is an InitVar, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses. For example, suppose a field will be initialized from a database, if a value is not provided when creating the class: @dataclass
class C:
    i: int
    j: int = None
    database: InitVar[DatabaseType] = None

    def __post_init__(self, database):
        if self.j is None and database is not None:
            self.j = database.lookup('j')

c = C(10, database=my_database)
 In this case, fields() will return Field objects for i and j, but not for database. Frozen instances It is not possible to create truly immutable Python objects. However, by passing frozen=True to the dataclass() decorator you can emulate immutability. In that case, dataclasses will add __setattr__() and __delattr__() methods to the class. These methods will raise a FrozenInstanceError when invoked. There is a tiny performance penalty when using frozen=True: __init__() cannot use simple assignment to initialize fields, and must use object.__setattr__(). Inheritance When the dataclass is being created by the dataclass() decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at object) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example: @dataclass
class Base:
    x: Any = 15.0
    y: int = 0

@dataclass
class C(Base):
    z: int = 10
    x: int = 15
 The final list of fields is, in order, x, y, z. The final type of x is int, as specified in class C. The generated __init__() method for C will look like: def __init__(self, x: int = 15, y: int = 0, z: int = 10):
 Default factory functions If a field() specifies a default_factory, it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use: mylist: list = field(default_factory=list)
 If a field is excluded from __init__() (using init=False) and the field also specifies default_factory, then the default factory function will always be called from the generated __init__() function. This happens because there is no other way to give the field an initial value. Mutable default values Python stores default member variable values in class attributes. Consider this example, not using dataclasses: class C:
    x = []
    def add(self, element):
        self.x.append(element)

o1 = C()
o2 = C()
o1.add(1)
o2.add(2)
assert o1.x == [1, 2]
assert o1.x is o2.x
 Note that the two instances of class C share the same class variable x, as expected. Using dataclasses, if this code was valid: @dataclass
class D:
    x: List = []
    def add(self, element):
        self.x += element
 it would generate code similar to: class D:
    x = []
    def __init__(self, x=x):
        self.x = x
    def add(self, element):
        self.x += element

assert D().x is D().x
 This has the same issue as the original example using class C. That is, two instances of class D that do not specify a value for x when creating a class instance will share the same copy of x. Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, dataclasses will raise a TypeError if it detects a default parameter of type list, dict, or set. This is a partial solution, but it does protect against many common errors. Using default factory functions is a way to create new instances of mutable types as default values for fields: @dataclass
class D:
    x: list = field(default_factory=list)

assert D().x is not D().x
 Exceptions
exception dataclasses.FrozenInstanceError
Raised when an implicitly defined __setattr__() or __delattr__() is called on a dataclass which was defined with frozen=True. It is a subclass of AttributeError.


dataclasses.asdict(instance, *, dict_factory=dict)
Converts the dataclass instance to a dict (by using the factory function dict_factory). Each dataclass is converted to a dict of its fields, as name: value pairs. dataclasses, dicts, lists, and tuples are recursed into. For example: @dataclass
class Point:
     x: int
     y: int

@dataclass
class C:
     mylist: list[Point]

p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}

c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
 Raises TypeError if instance is not a dataclass instance.


dataclasses.astuple(instance, *, tuple_factory=tuple)
Converts the dataclass instance to a tuple (by using the factory function tuple_factory). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, lists, and tuples are recursed into. Continuing from the previous example: assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)
 Raises TypeError if instance is not a dataclass instance.


@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
This function is a decorator that is used to add generated special methods to classes, as described below. The dataclass() decorator examines the class to find fields. A field is defined as class variable that has a type annotation. With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation. The order of the fields in all of the generated methods is the order in which they appear in the class definition. The dataclass() decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist on the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that is called on; no new class is created. If dataclass() is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of dataclass() are equivalent: @dataclass
class C:
    ...

@dataclass()
class C:
    ...

@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class C:
   ...
 The parameters to dataclass() are:
init: If true (the default), a __init__() method will be generated. If the class already defines __init__(), this parameter is ignored.
repr: If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10). If the class already defines __repr__(), this parameter is ignored.
eq: If true (the default), an __eq__() method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If the class already defines __eq__(), this parameter is ignored.
order: If true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised. If the class already defines any of __lt__(), __le__(), __gt__(), or __ge__(), then TypeError is raised.
unsafe_hash: If False (the default), a __hash__() method is generated according to how eq and frozen are set. __hash__() is used by built-in hash(), and when objects are added to hashed collections such as dictionaries and sets. Having a __hash__() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of __eq__(), and the values of the eq and frozen flags in the dataclass() decorator. By default, dataclass() will not implicitly add a __hash__() method unless it is safe to do so. Neither will it add or change an existing explicitly defined __hash__() method. Setting the class attribute __hash__ = None has a specific meaning to Python, as described in the __hash__() documentation. If __hash__() is not explicitly defined, or if it is set to None, then dataclass() may add an implicit __hash__() method. Although not recommended, you can force dataclass() to create a __hash__() method with unsafe_hash=True. This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully. Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True; this will result in a TypeError. If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None, marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object, this means it will fall back to id-based hashing).
frozen: If true (the default is False), assigning to fields will generate an exception. This emulates read-only frozen instances. If __setattr__() or __delattr__() is defined in the class, then TypeError is raised. See the discussion below.  fields may optionally specify a default value, using normal Python syntax: @dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'
 In this example, both a and b will be included in the added __init__() method, which will be defined as: def __init__(self, a: int, b: int = 0):
 TypeError will be raised if a field without a default value follows a field with a default value. This is true either when this occurs in a single class, or as a result of class inheritance.


class dataclasses.Field
Field objects describe each defined field. These objects are created internally, and are returned by the fields() module-level method (see below). Users should never instantiate a Field object directly. Its documented attributes are:
name: The name of the field.
type: The type of the field.
default, default_factory, init, repr, hash, compare, and metadata have the identical meaning and values as they do in the field() declaration.  Other attributes may exist, but they are private and must not be inspected or relied on.


dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function. For example: @dataclass
class C:
    mylist: list[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]
 As shown above, the MISSING value is a sentinel object used to detect if the default and default_factory parameters are provided. This sentinel is used because None is a valid value for default. No code should directly use the MISSING value. The parameters to field() are:
default: If provided, this will be the default value for this field. This is needed because the field() call itself replaces the normal position of the default value.
default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory.
init: If true (the default), this field is included as a parameter to the generated __init__() method.
repr: If true (the default), this field is included in the string returned by the generated __repr__() method.
compare: If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.).
hash: This can be a bool or None. If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare: this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged. One possible reason to set hash=False but compare=True would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.
metadata: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.  If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified default value. If no default is provided, then the class attribute will be deleted. The intent is that after the dataclass() decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after: @dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20
 The class attribute C.z will be 10, the class attribute C.t will be 20, and the class attributes C.x and C.y will not be set.


dataclasses.fields(class_or_instance)
Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises TypeError if not passed a dataclass or instance of one. Does not return pseudo-fields which are ClassVar or InitVar.


exception dataclasses.FrozenInstanceError
Raised when an implicitly defined __setattr__() or __delattr__() is called on a dataclass which was defined with frozen=True. It is a subclass of AttributeError.


dataclasses.is_dataclass(class_or_instance)
Return True if its parameter is a dataclass or an instance of one, otherwise return False. If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for not
isinstance(obj, type): def is_dataclass_instance(obj):
    return is_dataclass(obj) and not isinstance(obj, type)


dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
Creates a new dataclass with name cls_name, fields as defined in fields, base classes as given in bases, and initialized with a namespace as given in namespace. fields is an iterable whose elements are each either name, (name, type), or (name, type, Field). If just name is supplied, typing.Any is used for type. The values of init, repr, eq, order, unsafe_hash, and frozen have the same meaning as they do in dataclass(). This function is not strictly required, because any Python mechanism for creating a new class with __annotations__ can then apply the dataclass() function to convert that class to a dataclass. This function is provided as a convenience. For example: C = make_dataclass('C',
                   [('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace={'add_one': lambda self: self.x + 1})
 Is equivalent to: @dataclass
class C:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1


dataclasses.replace(instance, /, **changes)
Creates a new object of the same type of instance, replacing fields with values from changes. If instance is not a Data Class, raises TypeError. If values in changes do not specify fields, raises TypeError. The newly returned object is created by calling the __init__() method of the dataclass. This ensures that __post_init__(), if present, is also called. Init-only variables without default values, if any exist, must be specified on the call to replace() so that they can be passed to __init__() and __post_init__(). It is an error for changes to contain any fields that are defined as having init=False. A ValueError will be raised in this case. Be forewarned about how init=False fields work during a call to replace(). They are not copied from the source object, but rather are initialized in __post_init__(), if they’re initialized at all. It is expected that init=False fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom replace() (or similarly named) method which handles instance copying.