Inbyggda funktioner

Python-tolken har ett antal inbyggda funktioner och typer som alltid är tillgängliga. De listas här i alfabetisk ordning.

Inbyggda funktioner

E
uppräkna()

F
flöde()

G
globaler()

H
harattr()

I
inmatning()
L
lokal()

M

N
nästa()

O
objekt()
öppna()

P
egenskap()




R
vända()
rund()

S
skiva()
sorterad()
statisk metod()
summa()

T
typ()

V

Z

_
abs(x)

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

aiter(async_iterable)

Returnerar en asynkron iterator för en asynkron iterabel. Motsvarar anrop av x.__aiter__().

Notera: Till skillnad från iter() har aiter() ingen variant med 2 argument.

Nyheter i version 3.10.

all(iterable)

Returnerar True om alla element i iterabeln är sanna (eller om iterabeln är tom). Likvärdig med:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
awaitable anext(async_iterator)
awaitable anext(async_iterator, default)

När den är väntad returneras nästa objekt från den angivna asynchronous iterator, eller standard om den är angiven och iteratorn är uttömd.

Detta är den asynkrona varianten av next()-byggstenen och fungerar på samma sätt.

Detta anropar __anext__()-metoden för async_iterator och returnerar en awaitable. Awaiting detta returnerar nästa värde i iteratorn. Om default anges returneras det om iteratorn är uttömd, annars uppstår StopAsyncIteration.

Nyheter i version 3.10.

any(iterable)

Returnerar True om något element i iterabeln är sant. Om iterabeln är tom returneras False. Likvärdig med:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
ascii(object)

Som repr(), returnera en sträng som innehåller en utskrivbar representation av ett objekt, men escape icke-ASCII-tecken i strängen som returneras av repr() med hjälp av \x, \u eller U\ escapes. Detta genererar en sträng som liknar den som returneras av repr() i Python 2.

bin(x)

Convert an integer number to a binary string prefixed with ”0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

Om prefixet ”0b” önskas eller inte, kan du använda något av följande sätt.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

Se även format() för mer information.

class bool(x=False)

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise, it returns True. The bool class is a subclass of int (see Numeriska typer — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).

Förändrat i version 3.7: x is now a positional-only parameter.

breakpoint(*args, **kws)

This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice. If sys.breakpointhook() is not accessible, this function will raise RuntimeError.

Som standard kan beteendet hos breakpoint() ändras med miljövariabeln PYTHONBREAKPOINT. Se sys.breakpointhook() för användningsdetaljer.

Observera att detta inte är garanterat om sys.breakpointhook() har ersatts.

Utlöser en auditing event builtins.breakpoint med argumentet breakpointhook.

Nyheter i version 3.7.

class bytearray(source=b'')
class bytearray(source, encoding)
class bytearray(source, encoding, errors)

Returnerar en ny array av bytes. Klassen bytearray är en föränderlig sekvens av heltal i intervallet 0 <= x < 256. Den har de flesta av de vanliga metoderna för muterbara sekvenser, beskrivna i Mutabla sekvenstyper, samt de flesta metoder som typen bytes har, se Bytes and Bytearray Operations.

Den valfria parametern source kan användas för att initiera matrisen på några olika sätt:

  • Om det är en sträng måste du också ange parametrarna encoding (och eventuellt errors); bytearray() konverterar sedan strängen till bytes med str.encode().

  • Om det är ett integer kommer arrayen att ha den storleken och initialiseras med null-bytes.

  • Om det är ett objekt som överensstämmer med buffer interface, kommer en skrivskyddad buffert av objektet att användas för att initiera bytesmatrisen.

  • Om det är en iterabel måste det vara en iterabel av heltal i intervallet 0 <= x < 256, som används som det ursprungliga innehållet i matrisen.

Utan argument skapas en array av storleken 0.

Se även Binary Sequence Types — bytes, bytearray, memoryview och Bytearray Objects.

class bytes(source=b'')
class bytes(source, encoding)
class bytes(source, encoding, errors)

Returnerar ett nytt ”bytes”-objekt som är en oföränderlig sekvens av heltal i intervallet 0 <= x < 256. bytes är en oföränderlig version av bytearray – den har samma icke-muterande metoder och samma indexerings- och skivningsbeteende.

Följaktligen tolkas konstruktörsargument som för bytearray().

Bytesobjekt kan också skapas med literaler, se String and Bytes literals.

Se även Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects och Bytes and Bytearray Operations.

callable(object)

Returnerar True om argumentet object verkar anropbart, False om inte. Om detta returnerar True är det fortfarande möjligt att ett anrop misslyckas, men om det är False kommer anropet av object aldrig att lyckas. Observera att klasser är anropsbara (anrop av en klass returnerar en ny instans); instanser är anropsbara om deras klass har en __call__()-metod.

Nyheter i version 3.2: Denna funktion togs först bort i Python 3.0 och återinfördes sedan i Python 3.2.

chr(i)

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

@classmethod

Omvandla en metod till en klassmetod.

En klassmetod tar emot klassen som ett implicit första argument, precis som en instansmetod tar emot instansen. För att deklarera en klassmetod använder du detta idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2): ...

Formuläret @classmethod är en funktion decorator – se Function definitions för detaljer.

En klassmetod kan anropas antingen på klassen (t.ex. C.f()) eller på en instans (t.ex. C().f()). Instansen ignoreras med undantag för dess klass. Om en klassmetod anropas för en härledd klass, skickas det härledda klassobjektet som det underförstådda första argumentet.

Klassmetoder är annorlunda än statiska metoder i C++ eller Java. Om du vill ha sådana, se staticmethod() i detta avsnitt. För mer information om klassmetoder, se The standard type hierarchy.

Förändrat i version 3.9: Klassmetoder kan nu omsluta andra deskriptorer såsom property().

Förändrat i version 3.10: Class methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__) and have a new __wrapped__ attribute.

Förändrat i version 3.11: Klassmetoder kan inte längre omsluta andra deskriptorer såsom property().

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Kompilera källan till ett kod- eller AST-objekt. Kodobjekt kan exekveras med exec() eller eval(). source kan antingen vara en normal sträng, en byte-sträng eller ett AST-objekt. Se dokumentationen för modulen ast för information om hur du arbetar med AST-objekt.

Argumentet filnamn ska ange den fil som koden lästes från; skicka något igenkännbart värde om den inte lästes från en fil ('<string>' används ofta).

Argumentet mode anger vilken typ av kod som ska kompileras; det kan vara 'exec' om källan består av en sekvens av satser, 'eval' om den består av ett enda uttryck, eller 'single' om den består av en enda interaktiv sats (i det senare fallet skrivs satser som utvärderas till något annat än None ut).

De valfria argumenten flags och dont_inherit styr vilka compiler options som ska aktiveras och vilka future features som ska tillåtas. Om ingen av dessa är närvarande (eller om båda är noll) kompileras koden med samma flaggor som påverkar koden som anropar compile(). Om argumentet flags anges och dont_inherit inte anges (eller är noll) används de kompilatoralternativ och framtida uttalanden som anges i argumentet flags utöver de som ändå skulle ha använts. Om dont_inherit är ett heltal som inte är noll så är flags-argumentet det - flaggorna (framtida funktioner och kompilatoralternativ) i den omgivande koden ignoreras.

Kompilatoralternativ och framtidssatser specificeras av bitar som kan kombineras bitvis för att specificera flera alternativ. Bitfältet som krävs för att specificera en given framtida funktion kan hittas som attributet compiler_flag_Feature instansen i __future__ modulen. Compiler flags kan hittas i ast modulen, med PyCF_ prefix.

Argumentet optimize anger kompilatorns optimeringsnivå; standardvärdet \-1 väljer tolkens optimeringsnivå som anges i -O-alternativen. Explicita nivåer är 0 (ingen optimering; __debug__ är sant), 1 (asserts tas bort, __debug__ är falskt) eller 2 (docstrings tas också bort).

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.

Om du vill analysera Python-kod till dess AST-representation, se ast.parse().

Utlöser en auditing-händelse compile med argumenten source och filename. Denna händelse kan också utlösas av implicit kompilering.

Observera

När en sträng med flerradig kod kompileras i läget 'single' eller 'eval' måste inmatningen avslutas med minst ett tecken för ny rad. Detta för att underlätta upptäckten av ofullständiga och fullständiga satser i modulen code.

Varning

Det är möjligt att krascha Python-tolken med en tillräckligt stor/komplex sträng när den kompileras till ett AST-objekt på grund av begränsningar i stackdjupet i Pythons AST-kompilator.

Förändrat i version 3.2: Tillåtet att använda Windows och Mac newlines. Dessutom behöver inmatning i 'exec'-läge inte längre avslutas med en ny rad. Parametern optimize har lagts till.

Förändrat i version 3.5: Tidigare skapades TypeError när null bytes påträffades i source.

Nyheter i version 3.8: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT can now be passed in flags to enable support for top-level await, async for, and async with.

class complex(real=0, imag=0)
class complex(string)

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

For a general Python object x, complex(x) delegates to x.__complex__(). If __complex__() is not defined then it falls back to __float__(). If __float__() is not defined then it falls back to __index__().

Observera

When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

The complex type is described in Numeriska typer — int, float, complex.

Förändrat i version 3.6: Grouping digits with underscores as in code literals is allowed.

Förändrat i version 3.8: Falls back to __index__() if __complex__() and __float__() are not defined.

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. name need not be a Python identifier (see setattr()).

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.

dir()
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']

Observera

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.

divmod(a, b)

Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

enumerate(iterable, start=0)

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Equivalent to:

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
eval(expression, globals=None, locals=None)

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to eval(). If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case, pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()'s return value will be None.

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions return the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().

If the given source is a string, then leading and trailing spaces and tabs are stripped.

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

exec(object, globals=None, locals=None, /, *, closure=None)

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section File input in the Reference Manual). Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().

The closure argument specifies a closure–a tuple of cellvars. It’s only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

Observera

The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().

Observera

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

Förändrat i version 3.11: Added the closure parameter.

filter(function, iterable)

Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function is false.

class float(x=0.0)

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. More precisely, the input must conform to the floatvalue production rule in the following grammar, after leading and trailing whitespace characters are removed:

sign        ::=  "+" | "-"
infinity    ::=  "Infinity" | "inf"
nan         ::=  "nan"
digit       ::=  <a Unicode decimal digit, i.e. characters in Unicode general category Nd>
digitpart   ::=  digit (["_"] digit)*
number      ::=  [digitpart] "." digitpart | digitpart ["."]
exponent    ::=  ("e" | "E") ["+" | "-"] digitpart
floatnumber ::=  number [exponent]
floatvalue  ::=  [sign] (floatnumber | infinity | nan)

Case is not significant, so, for example, ”inf”, ”Inf”, ”INFINITY”, and ”iNfINity” are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().

If no argument is given, 0.0 is returned.

Examples:

>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

The float type is described in Numeriska typer — int, float, complex.

Förändrat i version 3.6: Grouping digits with underscores as in code literals is allowed.

Förändrat i version 3.7: x is now a positional-only parameter.

Förändrat i version 3.8: Falls back to __index__() if __float__() is not defined.

format(value, format_spec='')

Convert a value to a ”formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

The default format_spec is an empty string which usually gives the same effect as calling str(value).

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Förändrat i version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.

class frozenset(iterable=set())

Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.

getattr(object, name)
getattr(object, name, default)

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. name need not be a Python identifier (see setattr()).

Observera

Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with getattr().

globals()

Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.

hasattr(object, name)

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

hash(object)

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Observera

For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine.

help()
help(request)

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking help(), it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.

This function is added to the built-in namespace by the site module.

Förändrat i version 3.4: Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.

hex(x)

Convert an integer number to a lowercase hexadecimal string prefixed with ”0x”. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

Se även format() för mer information.

See also int() for converting a hexadecimal string to an integer using a base of 16.

Observera

To obtain a hexadecimal string representation for a float, use the float.hex() method.

id(object)

Return the ”identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

Detaljerad implementering av CPython: This is the address of the object in memory.

Raises an auditing event builtins.id with argument id.

input()
input(prompt)

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Raises an auditing event builtins.input with argument prompt before reading input

Raises an auditing event builtins.input/result with the result after successfully reading input.

class int(x=0)
class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer in radix base. Optionally, the string can be preceded by + or - (with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.

A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0–9 can be represented by any Unicode decimal digit. The values 10–35 can be represented by a to z (or A to Z). The default base is 10. The allowed bases are 0 and 2–36. Base-2, -8, and -16 strings can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. For base 0, the string is interpreted in a similar way to an integer literal in code, in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros: int('010', 0) is not legal, while int('010') and int('010', 8) are.

The integer type is described in Numeriska typer — int, float, complex.

Förändrat i version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.

Förändrat i version 3.6: Grouping digits with underscores as in code literals is allowed.

Förändrat i version 3.7: x is now a positional-only parameter.

Förändrat i version 3.8: Falls back to __index__() if __int__() is not defined.

Förändrat i version 3.11: The delegation to __trunc__() is deprecated.

Förändrat i version 3.11: int string inputs and string representations can be limited to help avoid denial of service attacks. A ValueError is raised when the limit is exceeded while converting a string x to an int or when converting an int into a string would exceed the limit. See the integer string conversion length limitation documentation.

isinstance(object, classinfo)

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Typ av fackförening of multiple types, return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised. TypeError may not be raised for an invalid type if an earlier check succeeds.

Förändrat i version 3.10: classinfo can be a Typ av fackförening.

issubclass(class, classinfo)

Return True if class is a subclass (direct, indirect, or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a Typ av fackförening, in which case return True if class is a subclass of any entry in classinfo. In any other case, a TypeError exception is raised.

Förändrat i version 3.10: classinfo can be a Typ av fackförening.

iter(object)
iter(object, sentinel)

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iterable protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

See also Iterator-typer.

One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:

from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b''):
        process_block(block)
len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Detaljerad implementering av CPython: len raises OverflowError on lengths larger than sys.maxsize, such as range(2 ** 100).

class list
class list(iterable)

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

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

Observera

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

map(function, iterable, *iterables)

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

max(iterable, *, key=None)
max(iterable, *, default, key=None)
max(arg1, arg2, *args, key=None)

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

Förändrat i version 3.4: Added the default keyword-only parameter.

Förändrat i version 3.8: The key can be None.

class memoryview(object)

Return a ”memory view” object created from the given argument. See Minnesvy for more information.

min(iterable, *, key=None)
min(iterable, *, default, key=None)
min(arg1, arg2, *args, key=None)

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc).

Förändrat i version 3.4: Added the default keyword-only parameter.

Förändrat i version 3.8: The key can be None.

next(iterator)
next(iterator, default)

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

class object

Return a new featureless object. object is a base for all classes. It has methods that are common to all instances of Python classes. This function does not accept any arguments.

Observera

object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

oct(x)

Convert an integer number to an octal string prefixed with ”0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

If you want to convert an integer number to an octal string either with the prefix ”0o” or not, you can use either of the following ways.

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

Se även format() för mer information.

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent: locale.getencoding() is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

Character

Meaning

'r'

open for reading (default)

'w'

open for writing, truncating the file first

'x'

öppen för exklusiv skapelse, misslyckas om filen redan finns

'a'

öppen för skrivning, läggs till i slutet av filen om den finns

'b'

binärt läge

't'

textläge (standard)

'+'

öppen för uppdatering (läsning och skrivning)

Standardläget är 'r' (öppen för läsning av text, en synonym till 'rt'). Lägena 'w+' och 'w+b' öppnar och trunkerar filen. Lägena 'r+' och 'r+b' öppnar filen utan trunkering.

Som nämndes i Overview skiljer Python mellan binär och text I/O. Filer som öppnas i binärt läge (inklusive 'b' i mode-argumentet) returnerar innehållet som bytes-objekt utan någon avkodning. I textläge (standard, eller när 't' ingår i mode-argumentet) returneras filens innehåll som str, där bytena först har avkodats med en plattformsberoende kodning eller med den angivna kodningen om den anges.

Observera

Python är inte beroende av det underliggande operativsystemets uppfattning om textfiler; all bearbetning görs av Python självt och är därför plattformsoberoende.

buffering är ett valfritt heltal som används för att ställa in buffringspolicyn. Ange 0 för att stänga av buffring (endast tillåtet i binärt läge), 1 för att välja linjebuffring (endast användbart när du skriver i textläge) och ett heltal > 1 för att ange storleken i byte på en buffert med fast storlek. Observera att om du anger en buffertstorlek på det här sättet gäller det för binärt buffrad I/O, men TextIOWrapper (dvs. filer som öppnas med mode='r+') skulle ha en annan buffring. För att inaktivera buffring i TextIOWrapper, överväg att använda write_through flaggan för io.TextIOWrapper.reconfigure(). När inget buffering-argument anges fungerar standardpolicyn för buffring på följande sätt:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s ”block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

  • ”Interaktiva” textfiler (filer för vilka isatty() returnerar True) använder radbuffring. Andra textfiler använder den policy som beskrivs ovan för binära filer.

encoding är namnet på den kodning som används för att avkoda eller koda filen. Detta bör endast användas i textläge. Standardkodningen är plattformsberoende (oavsett vad locale.getencoding() returnerar), men alla text encoding som stöds av Python kan användas. Se modulen codecs för en lista över kodningar som stöds.

errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.

  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.

  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.

  • 'surrogateescape' will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.

  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.

  • 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences.

  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.

newline bestämmer hur man analyserar nya radtecken från flödet. Det kan vara None, '', '\n', '\r' och '\r\n'. Det fungerar på följande sätt:

  • Om newline är None aktiveras universal newlines-läget när indata läses från strömmen. Rader i inmatningen kan sluta på '\n', '\r' eller '\r\n', och dessa översätts till '\n' innan de returneras till den som anropar. Om det är '' aktiveras universal newlines mode, men radavslut returneras till uppringaren oöversatta. Om det har något av de andra lagliga värdena avslutas inmatningsraderna endast med den angivna strängen, och radavslutningen returneras till den som ringer upp oöversatt.

  • Om newline är None när utdata skrivs till strömmen, översätts alla '\n'-tecken som skrivs till systemets standardradavgränsare, os.linesep. Om newline är '' eller '\n' sker ingen översättning. Om newline är något av de andra lagliga värdena översätts alla '\n'-tecken som skrivs till den angivna strängen.

Om closefd är False och en filbeskrivare istället för ett filnamn har angetts, kommer den underliggande filbeskrivaren att hållas öppen när filen stängs. Om ett filnamn anges måste closefd vara True (standard), annars kommer ett fel att uppstå.

En anpassad öppnare kan användas genom att skicka en anropsbar som opener. Den underliggande filbeskrivaren för filobjektet erhålls sedan genom att anropa opener med (file, flags). opener måste returnera en öppen filbeskrivare (att skicka os.open som opener resulterar i funktionalitet som liknar att skicka None).

Den nyskapade filen är icke-ärftlig.

I följande exempel används parametern dir_fd i funktionen os.open() för att öppna en fil i förhållande till en viss katalog:

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

Typen av file object som returneras av funktionen open() beror på läget. När open() används för att öppna en fil i textläge ('w', 'r', 'wt', 'rt', etc.) returneras en underklass av io.TextIOBase (specifikt io.TextIOWrapper). När den används för att öppna en fil i binärt läge med buffring är den returnerade klassen en underklass till io.BufferedIOBase. Den exakta klassen varierar: i binärt läsläge returneras en io.BufferedReader, i binärt skrivläge och binärt append-läge returneras en io.BufferedWriter och i läs-/skrivläge returneras en io.BufferedRandom. När buffringen är inaktiverad returneras råströmmen, en underklass till io.RawIOBase, io.FileIO.

Se även filhanteringsmodulerna, till exempel fileinput, io (där open() deklareras), os, os.path, tempfile och shutil.

Raises an auditing event open with arguments file, mode, flags.

Argumenten mode och flags kan ha ändrats eller härletts från det ursprungliga anropet.

Förändrat i version 3.3:

  • Parametern opener har lagts till.

  • Läget 'x' lades till.

  • IOError användes tidigare, nu är det ett alias för OSError.

  • FileExistsError visas nu om filen som öppnades i exklusivt skapande-läge ('x') redan existerar.

Förändrat i version 3.4:

  • Filen är nu inte ärftlig.

Förändrat i version 3.5:

  • Om systemanropet avbryts och signalhanteraren inte ger upphov till ett undantag, försöker funktionen nu göra om systemanropet istället för att ge upphov till ett InterruptedError-undantag (se PEP 475 för förklaringen).

  • Felhanteraren 'namereplace' har lagts till.

Förändrat i version 3.6:

  • Stöd har lagts till för att acceptera objekt som implementerar os.PathLike.

  • I Windows kan öppnandet av en konsolbuffert returnera en annan underklass av io.RawIOBase än io.FileIO.

Förändrat i version 3.11: Läget 'U har tagits bort.

ord(c)

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

pow(base, exp, mod=None)

Returnerar bas till potensen exp; om mod finns, returneras bas till potensen exp, modulo mod (beräknas effektivare än pow(bas, exp) % mod). Formen pow(base, exp) med två argument är likvärdig med att använda potensoperatorn: base**exp.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, pow(10, 2) returns 100, but pow(10, -2) returns 0.01. For a negative base of type int or float and a non-integral exponent, a complex result is delivered. For example, pow(-9, 0.5) returns a value close to 3j.

För int-operanderna base och exp gäller att om mod förekommer måste mod också vara av heltalstyp och mod måste vara icke-noll. Om mod finns och exp är negativ, måste base vara relativt primtal till mod. I så fall returneras pow(inv_base, -exp, mod), där inv_base är en invers till base modulo mod.

Här är ett exempel på att beräkna en invers för 38 modulo 97:

>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True

Förändrat i version 3.8: För int-operander tillåter nu treargumentformen av pow att det andra argumentet är negativt, vilket möjliggör beräkning av modulära inverser.

Förändrat i version 3.8: Tillåt nyckelordsargument. Tidigare stöddes endast positionella argument.

print(*objects, sep=' ', end='\n', file=None, flush=False)

Skriver ut objekt till textflödet file, separerade med sep och följda av end. sep, end, file och flush, om de finns, måste anges som nyckelordsargument.

Alla argument som inte är nyckelord konverteras till strängar som str() gör och skrivs till strömmen, separerade med sep och följda av end. Både sep och end måste vara strängar; de kan också vara None, vilket innebär att standardvärdena används. Om inga objekt anges kommer print() bara att skriva end.

Argumentet file måste vara ett objekt med en write(string)-metod; om det inte finns eller om det är None, kommer sys.stdout att användas. Eftersom utskrivna argument konverteras till textsträngar kan print() inte användas med filobjekt i binärt läge. För dessa används istället file.write(...).

Buffring av utdata bestäms vanligtvis av file. Men om flush är true, spolas strömmen med våld.

Förändrat i version 3.3: Lagt till nyckelordsargumentet flush.

class property(fget=None, fset=None, fdel=None, doc=None)

Returnerar ett egenskapsattribut.

fget är en funktion för att hämta ett attributvärde. fset är en funktion för att ställa in ett attributvärde. fdel är en funktion för att ta bort ett attributvärde. Och doc skapar en docstring för attributet.

En typisk användning är att definiera ett hanterat attribut x:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

Om c är en instans av C, kommer c.x att anropa getter, c.x = value kommer att anropa setter och del c.x deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget’s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

Dekoratorn @property förvandlar metoden voltage() till en ”getter” för ett skrivskyddat attribut med samma namn och sätter docstring för voltage till ”Get the current voltage”

@getter
@setter
@deleter

Ett egenskapsobjekt har metoderna getter, etter och deleter som kan användas som dekoratorer som skapar en kopia av egenskapen med motsvarande accessorfunktion inställd på den dekorerade funktionen. Detta förklaras bäst med ett exempel:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Denna kod är exakt likvärdig med det första exemplet. Var noga med att ge de ytterligare funktionerna samma namn som den ursprungliga egenskapen (x i det här fallet.)

Det returnerade egenskapsobjektet har också attributen fget, fset och fdel som motsvarar konstruktörens argument.

Förändrat i version 3.5: Dokumentationen av property-objekt är nu skrivbar.

class range(stop)
class range(start, stop, step=1)

I stället för att vara en funktion är range faktiskt en oföränderlig sekvenstyp, vilket dokumenteras i Ranges och Sekvenstyper — list, tuple, range.

repr(object)

Returnerar en sträng som innehåller en utskriftsvänlig representation av ett objekt. För många typer försöker denna funktion returnera en sträng som skulle ge ett objekt med samma värde när den skickas till eval(); annars är representationen en sträng inom hakparenteser som innehåller namnet på objektets typ tillsammans med ytterligare information, ofta inklusive objektets namn och adress. En klass kan styra vad denna funktion returnerar för sina instanser genom att definiera en __repr__()-metod. Om sys.displayhook() inte är tillgänglig kommer denna funktion att ge upphov till RuntimeError.

Denna klass har en anpassad representation som kan utvärderas:

class Person:
   def __init__(self, name, age):
      self.name = name
      self.age = age

   def __repr__(self):
      return f"Person('{self.name}', {self.age})"
reversed(seq)

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

round(number, ndigits=None)

Returnerar tal avrundat till siffrors precision efter decimaltecknet. Om ndigits utelämnas eller är None, returneras det närmaste heltalet till indata.

För de inbyggda typer som stöder round() avrundas värden till närmaste multipel av 10 i potens minus ndigits; om två multiplar är lika nära avrundas till det jämna valet (så till exempel är både round(0.5) och round(-0.5) 0, och round(1.5) är 2). Alla heltalsvärden är giltiga för siffror (positiva, noll eller negativa). Returvärdet är ett heltal om ndigits utelämnas eller None. I annat fall har returvärdet samma typ som number.

För ett allmänt Python-objekt number delegerar round till number.__round__.

Observera

Beteendet hos round() för flyttal kan vara överraskande: till exempel ger round(2,675, 2) 2,67 istället för det förväntade 2,68. Detta är inte en bugg: det är ett resultat av det faktum att de flesta decimalfraktioner inte kan representeras exakt som ett flyttal. Se Floating Point Arithmetic: Issues and Limitations för mer information.

class set
class set(iterable)

Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

För andra behållare se de inbyggda klasserna frozenset, list, tuple och dict, samt modulen collections.

setattr(object, name, value)

Detta är motsvarigheten till getattr(). Argumenten är ett objekt, en sträng och ett godtyckligt värde. Strängen kan namnge ett befintligt attribut eller ett nytt attribut. Funktionen tilldelar värdet till attributet, förutsatt att objektet tillåter det. Exempelvis är setattr(x, 'foobar', 123) likvärdigt med x.foobar = 123.

name behöver inte vara en Python-identifierare enligt definitionen i Identifiers and keywords om inte objektet väljer att tillämpa detta, t.ex. i en anpassad __getattribute__() eller via __slots__. Ett attribut vars namn inte är en identifierare kommer inte att vara tillgängligt med hjälp av punktnotationen, men är tillgängligt via getattr() etc.

Observera

Eftersom private name mangling sker vid kompilering måste man manuellt mangla ett privat attributs (attribut med två inledande understreck) namn för att kunna ställa in det med setattr().

class slice(stop)
class slice(start, stop, step=None)

Returnerar ett slice-objekt som representerar den uppsättning index som anges av range(start, stop, step). Argumenten start och step är som standard None.

start
stop
step

Slice objects have read-only data attributes start, stop, and step which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages.

Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

sorted(iterable, /, *, key=None, reverse=False)

Returnerar en ny sorterad lista från objekten i iterable.

Har två valfria argument som måste anges som nyckelordsargument.

key anger en funktion med ett argument som används för att extrahera en jämförelsenyckel från varje element i iterable (t.ex. key=str.lower). Standardvärdet är None (jämför elementen direkt).

reverse är ett booleanskt värde. Om värdet är satt till True sorteras listelementen som om varje jämförelse vore omvänd.

Använd functools.cmp_to_key() för att konvertera en gammaldags cmp-funktion till en key-funktion.

Den inbyggda funktionen sorted() är garanterat stabil. En sortering är stabil om den garanterar att den inte ändrar den relativa ordningen för element som jämförs lika — detta är användbart för sortering i flera omgångar (t.ex. sortera efter avdelning, sedan efter lönegrad).

The sort algorithm uses only < comparisons between items. While defining an __lt__() method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented. This will help avoid bugs when using the same data with other ordering tools such as max() that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the __gt__() method.

För sorteringsexempel och en kort sorteringshandledning, se Sorting HOW TO.

@staticmethod

Omvandla en metod till en statisk metod.

En statisk metod får inte något implicit första argument. För att deklarera en statisk metod, använd detta idiom:

class C:
    @staticmethod
    def f(arg1, arg2, argN): ...

Formen @staticmethod är en funktion decorator – se Function definitions för detaljer.

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, they can be called as regular functions (such as f()).

Static methods in Python are similar to those found in Java or C++. Also, see classmethod() for a variant that is useful for creating alternate class constructors.

Som alla dekoratorer är det också möjligt att anropa staticmethod som en vanlig funktion och göra något med dess resultat. Detta behövs i vissa fall där du behöver en referens till en funktion från en klass och du vill undvika den automatiska omvandlingen till instansmetod. För dessa fall, använd detta idiom:

def regular_function():
    ...

class C:
    method = staticmethod(regular_function)

För mer information om statiska metoder, se The standard type hierarchy.

Förändrat i version 3.10: Static methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__), have a new __wrapped__ attribute, and are now callable as regular functions.

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

Returnerar en str-version av object. Se str() för detaljer.

str är den inbyggda strängen class. För allmän information om strängar, se Text Sequence Type — str.

sum(iterable, /, start=0)

Summerar start och posterna i en iterabel från vänster till höger och returnerar totalsumman. Posterna i iterabeln är normalt tal och startvärdet får inte vara en sträng.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

Förändrat i version 3.8: Parametern start kan anges som ett nyckelordsargument.

class super
class super(type, object_or_type=None)

Returnerar ett proxyobjekt som delegerar metodanrop till en överordnad eller syskonklass av typ. Detta är användbart för att komma åt ärvda metoder som har åsidosatts i en klass.

Object_or_type bestämmer vilken method resolution order som ska sökas. Sökningen börjar från klassen direkt efter typ.

For example, if __mro__ of object_or_type is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.

The __mro__ attribute of the object_or_type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

Om det andra argumentet utelämnas är det superobjekt som returneras obundet. Om det andra argumentet är ett objekt måste isinstance(obj, type) vara true. Om det andra argumentet är en typ måste issubclass(type2, type) vara true (detta är användbart för classmethods).

Det finns två typiska användningsområden för super. I en klasshierarki med enkel nedärvning kan super användas för att hänvisa till överordnade klasser utan att namnge dem explicit, vilket gör koden mer lätthanterlig. Denna användning är nära parallell med användningen av super i andra programmeringsspråk.

Det andra användningsfallet är att stödja kooperativ multipel nedärvning i en dynamisk exekveringsmiljö. Detta användningsfall är unikt för Python och finns inte i statiskt kompilerade språk eller språk som bara stöder enkel arvbarhet. Detta gör det möjligt att implementera ”diamantdiagram” där flera basklasser implementerar samma metod. God design kräver att sådana implementationer har samma anropssignatur i samtliga fall (eftersom anropsordningen bestäms vid körning, eftersom denna ordning anpassas till förändringar i klasshierarkin och eftersom denna ordning kan omfatta syskonklasser som är okända före körning).

För båda användningsfallen ser ett typiskt superklassanrop ut så här:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

Förutom metoduppslagningar fungerar super() också för attributuppslagningar. Ett möjligt användningsfall för detta är att anropa descriptors i en överordnad eller syskonklass.

Observera att super() implementeras som en del av bindningsprocessen för uttryckliga prickade attributuppslagningar som super().__getitem__(name). Den gör detta genom att implementera sin egen __getattribute__()-metod för att söka klasser i en förutsägbar ordning som stöder kooperativ multipel nedärvning. Följaktligen är super() odefinierad för implicita uppslagningar med satser eller operatorer som super()[name].

Observera också att super(), bortsett från formen med noll argument, inte är begränsad till att användas inuti metoder. Formen med två argument specificerar argumenten exakt och gör lämpliga referenser. Formen med nollargument fungerar bara inuti en klassdefinition, eftersom kompilatorn fyller i de nödvändiga detaljerna för att korrekt hämta den klass som definieras, samt för att komma åt den aktuella instansen för vanliga metoder.

För praktiska förslag på hur man utformar kooperativa klasser med hjälp av super(), se guide to using super().

class tuple
class tuple(iterable)

I stället för att vara en funktion är tuple faktiskt en oföränderlig sekvenstyp, vilket dokumenteras i Tuples och Sekvenstyper — list, tuple, range.

class type(object)
class type(name, bases, dict, **kwds)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

Den inbyggda funktionen isinstance() rekommenderas för att testa typen av ett objekt, eftersom den tar hänsyn till underklasser.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute. The bases tuple contains the base classes and becomes the __bases__ attribute; if empty, object, the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the __dict__ attribute. The following two statements create identical type objects:

>>> class X:
...     a = 1
...
>>> X = type('X', (), dict(a=1))

See also Typ av objekt.

Nyckelordsargument som anges i formuläret med tre argument skickas till lämplig metaklassmekanism (vanligtvis __init_subclass__()) på samma sätt som nyckelord i en klassdefinition (förutom metaklass).

Se även Customizing class creation.

Förändrat i version 3.6: Subclasses of type which don’t override type.__new__ may no longer use the one-argument form to get the type of an object.

vars()
vars(object)

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

Ett undantag av typen TypeError uppstår om ett objekt anges men det inte har något attribut __dict__ (t.ex. om dess klass definierar attributet __slots__).

zip(*iterables, strict=False)

Iterera över flera iterabler parallellt och producera tuples med ett objekt från var och en.

Exempel:

>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
...     print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')

Mer formellt: zip() returnerar en iterator av tupler, där den i:e tupeln innehåller det i:e elementet från var och en av argumentets iterabler.

Ett annat sätt att tänka på zip() är att den förvandlar rader till kolumner och kolumner till rader. Detta liknar transponering av en matris.

zip() är lat: Elementen kommer inte att bearbetas förrän iterabeln itereras, t.ex. genom en for-loop eller genom att packas in i en list.

En sak att tänka på är att de iterabler som skickas till zip() kan ha olika längd; ibland på grund av design, och ibland på grund av en bugg i koden som förberedde dessa iterabler. Python erbjuder tre olika sätt att hantera detta problem:

  • Som standard stoppar zip() när den kortaste iterabeln är uttömd. Den ignorerar de återstående objekten i de längre iterationerna och skär av resultatet till längden på den kortaste iterationen:

    >>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
    [(0, 'fee'), (1, 'fi'), (2, 'fo')]
    
  • zip() is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use the strict=True option. Its output is the same as regular zip():

    >>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
    [('a', 1), ('b', 2), ('c', 3)]
    

    Unlike the default behavior, it raises a ValueError if one iterable is exhausted before the others:

    >>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True):  
    ...     print(item)
    ...
    (0, 'fee')
    (1, 'fi')
    (2, 'fo')
    Traceback (most recent call last):
      ...
    ValueError: zip() argument 2 is longer than argument 1
    

    Without the strict=True argument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.

  • Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by itertools.zip_longest().

Edge cases: With a single iterable argument, zip() returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

Tips and tricks:

  • The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n, strict=True). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

  • zip() in conjunction with the * operator can be used to unzip a list:

    >>> x = [1, 2, 3]
    >>> y = [4, 5, 6]
    >>> list(zip(x, y))
    [(1, 4), (2, 5), (3, 6)]
    >>> x2, y2 = zip(*zip(x, y))
    >>> x == list(x2) and y == list(y2)
    True
    

Förändrat i version 3.10: Added the strict argument.

__import__(name, globals=None, locals=None, fromlist=(), level=0)

Observera

This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], 0)

The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], 0)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

Förändrat i version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).

Förändrat i version 3.9: When the command line options -E or -I are being used, the environment variable PYTHONCASEOK is now ignored.

Footnotes