Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

3.11.

2 Go

Built-in Functions
T he Pyt hon int erpret er has a number of funct ions and t ypes built into it t hat are always available. T hey are
list ed here in alphabet ical order.

Built-in Functions

A E L R
abs() enumerate() len() range()
aiter() eval() list() repr()
all() exec() locals() reversed()
any() round()
anext() F M
ascii() filter() map() S
float() max() set()
B format() memoryview() setattr()
bin() frozenset() min() slice()
bool() sorted()
breakpoint() G N staticmethod()
bytearray() getattr() next() str()
bytes() globals() sum()
O super()
C H object()
callable() hasattr() oct() T
chr() hash() open() tuple()
classmethod() help() ord() type()
compile() hex()
complex() P V
I pow() vars()
D id() print()
delattr() input() property() Z
dict() int() zip()
dir() isinstance()
divmod() issubclass() _
iter() __import__()

abs(x)
Ret urn t he absolut e value of a number. T he argument may be an int eger, a float ing point number, or an
object implement ing __abs__() . If t he argument is a complex number, it s magnit ude is ret urned.

aiter(async_iterable)
Ret urn an asynchronous it erator for an asynchronous it erable. Equivalent to calling x.__aiter__() .

Not e: Unlike iter() , aiter() has no 2-argument variant .

New in version 3.10.

all(iterable)
Ret urn True if all element s of t he iterable are t rue (or if t he it erable is empt y). Equivalent to:

def all(iterable):
for element in iterable:
if not element:
return False
return True
awaitable anext(async_iterator)
awaitable anext(async_iterator, default)
When await ed, ret urn t he next it em from t he given asynchronous it erator, or default if given and t he
it erator is exhaust ed.

T his is t he async variant of t he next() built in, and behaves similarly.

T his calls t he __anext__() met hod of async_iterator, ret urning an await able. Await ing t his ret urns
t he next value of t he it erator. If default is given, it is ret urned if t he it erator is exhaust ed, ot herwise
StopAsyncIteration is raised.

New in version 3.10.

any(iterable)
Ret urn True if any element of t he iterable is t rue. If t he it erable is empt y, ret urn False . Equivalent to:

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

ascii(object)
As repr() , ret urn a st ring cont aining a print able represent at ion of an object , but escape t he non-
ASCII charact ers in t he st ring ret urned by repr() using \x , \u , or \U escapes. T his generat es a st ring
similar to t hat ret urned by repr() in Pyt hon 2.

bin(x)
Convert an int eger number to a binary st ring prefixed wit h “0b”. T he result is a valid Pyt hon expression.
If x is not a Pyt hon int object , it has to define an __index__() met hod t hat ret urns an int eger. Some
examples:

>>> bin(3) >>>


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

If t he prefix “0b” is desired or not , you can use eit her of t he following ways.

>>> format(14, '#b'), format(14, 'b') >>>


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

See also format() for more informat ion.

class bool(x=False)
Ret urn a Boolean value, i.e. one of True or False . x is convert ed using t he st andard t rut h t est ing
procedure. If x is false or omit t ed, t his ret urns False ; ot herwise, it ret urns True . T he bool class is a
subclass of int (see Numeric Types — int , float , complex). It cannot be subclassed furt her. It s only
inst ances are False and True (see Boolean Values).

Changed in version 3.7: x is now a posit ional-only paramet er.

breakpoint(*args, **kws)
T his funct ion drops you into t he debugger at t he call sit e. Specifically, it calls
sys.breakpointhook() , passing args and kws st raight t hrough. By default ,
sys.breakpointhook() calls pdb.set_trace() expect ing no argument s. In t his case, it is purely a
convenience funct ion so you don’t have to explicit ly import pdb or t ype as much code to ent er t he
debugger. However, sys.breakpointhook() can be set to some ot her funct ion and breakpoint()
will automat ically call t hat , allowing you to drop into t he debugger of choice. If
sys.breakpointhook() is not accessible, t his funct ion will raise RuntimeError .

Raises an audit ing event builtins.breakpoint wit h argument breakpointhook .

New in version 3.7.

class bytearray(source=b'')
class bytearray(source, encoding)
class bytearray(source, encoding, errors)
Ret urn a new array of byt es. T he bytearray class is a mut able sequence of int egers in t he range 0 <=
x < 256. It has most of t he usual met hods of mut able sequences, described in Mut able Sequence
Types, as well as most met hods t hat t he bytes t ype has, see Byt es and Byt earray Operat ions.

T he opt ional source paramet er can be used to init ialize t he array in a few different ways:

If it is a string, you must also give t he encoding (and opt ionally, errors ) paramet ers; bytearray()
t hen convert s t he st ring to byt es using str.encode() .
If it is an integer, t he array will have t hat size and will be init ialized wit h null byt es.
If it is an object conforming to t he buffer int erface, a read-only buffer of t he object will be used to
init ialize t he byt es array.
If it is an iterable, it must be an it erable of int egers in t he range 0 <= x < 256 , which are used as
t he init ial cont ent s of t he array.

Wit hout an argument , an array of size 0 is creat ed.

See also Binary Sequence Types — byt es, byt earray, memoryview and Byt earray Object s.

class bytes(source=b'')
class bytes(source, encoding)
class bytes(source, encoding, errors)
Ret urn a new “byt es” object which is an immut able sequence of int egers in t he range 0 <= x < 256 .
bytes is an immut able version of bytearray – it has t he same non-mut at ing met hods and t he same
indexing and slicing behavior.

Accordingly, const ructor argument s are int erpret ed as for bytearray() .

Byt es object s can also be creat ed wit h lit erals, see St ring and Byt es lit erals.

See also Binary Sequence Types — byt es, byt earray, memoryview, Byt es Object s, and Byt es and
Byt earray Operat ions.

callable(object)
Ret urn True if t he object argument appears callable, False if not . If t his ret urns True , it is st ill
possible t hat a call fails, but if it is False , calling object will never succeed. Not e t hat classes are
callable (calling a class ret urns a new inst ance); inst ances are callable if t heir class has a
__call__() met hod.

New in version 3.2: T his funct ion was first removed in Pyt hon 3.0 and t hen brought back in Pyt hon 3.2.

chr(i)
Ret urn t he st ring represent ing a charact er whose Unicode code point is t he int eger i. For example,
chr(97) ret urns t he st ring 'a' , while chr(8364) ret urns t he st ring '€' . T his is t he inverse of ord() .

T he valid range for t he argument is from 0 t hrough 1,114,111 (0x10FFFF in base 16). ValueError will
be raised if i is out side t hat range.

@classmethod
Transform a met hod into a class met hod.

A class met hod receives t he class as an implicit first argument , just like an inst ance met hod receives
t he inst ance. To declare a class met hod, use t his idiom:

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

T he @classmethod form is a funct ion decorator – see Funct ion definit ions for det ails.

A class met hod can be called eit her on t he class (such as C.f() ) or on an inst ance (such as
C().f() ). T he inst ance is ignored except for it s class. If a class met hod is called for a derived class,
t he derived class object is passed as t he implied first argument .

Class met hods are different t han C++ or Java st at ic met hods. If you want t hose, see
staticmethod() in t his sect ion. For more informat ion on class met hods, see T he st andard t ype
hierarchy.

Changed in version 3.9: Class met hods can now wrap ot her descriptors such as property() .

Changed in version 3.10: Class met hods now inherit t he met hod at t ribut es ( __module__ , __name__ ,
__qualname__ , __doc__ and __annotations__ ) and have a new __wrapped__ at t ribut e.

Changed in version 3.11: Class met hods can no longer wrap ot her descriptors such as property() .

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


Compile t he source into a code or AST object . Code object s can be execut ed by exec() or eval() .
source can eit her be a normal st ring, a byt e st ring, or an AST object . Refer to t he ast module
document at ion for informat ion on how to work wit h AST object s.

T he filename argument should give t he file from which t he code was read; pass some recognizable
value if it wasn’t read from a file ( '<string>' is commonly used).

T he mode argument specifies what kind of code must be compiled; it can be 'exec' if source
consist s of a sequence of st at ement s, 'eval' if it consist s of a single expression, or 'single' if it
consist s of a single int eract ive st at ement (in t he lat t er case, expression st at ement s t hat evaluat e
to somet hing ot her t han None will be print ed).

T he opt ional argument s flags and dont_inherit cont rol which compiler opt ions should be act ivat ed and
which fut ure feat ures should be allowed. If neit her is present (or bot h are zero) t he code is compiled
wit h t he same flags t hat affect t he code t hat is calling compile() . If t he flags argument is given and
dont_inherit is not (or is zero) t hen t he compiler opt ions and t he fut ure st at ement s specified by t he
flags argument are used in addit ion to t hose t hat would be used anyway. If dont_inherit is a non-zero
int eger t hen t he flags argument is it – t he flags (fut ure feat ures and compiler opt ions) in t he
surrounding code are ignored.

Compiler opt ions and fut ure st at ement s are specified by bit s which can be bit wise ORed toget her to
specify mult iple opt ions. T he bit field required to specify a given fut ure feat ure can be found as t he
compiler_flag at t ribut e on t he _Feature inst ance in t he __future__ module. Compiler flags can
be found in ast module, wit h PyCF_ prefix.

T he argument optimize specifies t he opt imizat ion level of t he compiler; t he default value of -1
select s t he opt imizat ion level of t he int erpret er as given by -O opt ions. Explicit levels are 0 (no
opt imizat ion; __debug__ is t rue), 1 (assert s are removed, __debug__ is false) or 2 (docst rings are
removed too).

T his funct ion raises SyntaxError if t he compiled source is invalid, and ValueError if t he source
cont ains null byt es.

If you want to parse Pyt hon code into it s AST represent at ion, see ast.parse() .

Raises an audit ing event compile wit h argument s source and filename . T his event may also be
raised by implicit compilat ion.

Note: When compiling a st ring wit h mult i-line code in 'single' or 'eval' mode, input must be
t erminat ed by at least one newline charact er. T his is to facilit at e det ect ion of incomplet e and
complet e st at ement s in t he code module.

Warning: It is possible to crash t he Pyt hon int erpret er wit h a sufficient ly large/complex st ring
when compiling to an AST object due to st ack dept h limit at ions in Pyt hon’s AST compiler.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also, input in 'exec' mode does
not have to end in a newline anymore. Added t he optimize paramet er.

Changed in version 3.5: Previously, TypeError was raised when null byt es were encount ered in source.

New in 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)
Ret urn a complex number wit h t he value real + imag*1j or convert a st ring or number to a complex
number. If t he first paramet er is a st ring, it will be int erpret ed as a complex number and t he funct ion
must be called wit hout a second paramet er. T he second paramet er can never be a st ring. Each
argument may be any numeric t ype (including complex). If imag is omit t ed, it default s to zero and t he
const ructor serves as a numeric conversion like int and float . If bot h argument s are omit t ed,
ret urns 0j .

For a general Pyt hon object x , complex(x) delegat es to x.__complex__() . If __complex__() is not
defined t hen it falls back to __float__() . If __float__() is not defined t hen it falls back to
__index__() .

Note: When convert ing from a st ring, t he st ring must not cont ain whit espace around t he cent ral
+ or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises
ValueError .

T he complex t ype is described in Numeric Types — int , float , complex.

Changed in version 3.6: Grouping digit s wit h underscores as in code lit erals is allowed.

Changed in version 3.8: Falls back to __index__() if __complex__() and __float__() are not
defined.
delattr(object, name)
T his is a relat ive of setattr() . T he argument s are an object and a st ring. T he st ring must be t he
name of one of t he object ’s at t ribut es. T he funct ion delet es t he named at t ribut e, provided t he object
allows it . For example, delattr(x, 'foobar') is equivalent to del x.foobar . name need not be a
Pyt hon ident ifier (see setattr() ).

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Creat e a new dict ionary. T he dict object is t he dict ionary class. See dict and Mapping Types — dict
for document at ion about t his class.

For ot her cont ainers see t he built -in list , set , and tuple classes, as well as t he collections
module.

dir()
dir(object)
Wit hout argument s, ret urn t he list of names in t he current local scope. Wit h an argument , at t empt to
ret urn a list of valid at t ribut es for t hat object .

If t he object has a met hod named __dir__() , t his met hod will be called and must ret urn t he list of
at t ribut es. T his allows object s t hat implement a custom __getattr__() or __getattribute__()
funct ion to customize t he way dir() report s t heir at t ribut es.

If t he object does not provide __dir__() , t he funct ion t ries it s best to gat her informat ion from t he
object ’s __dict__ at t ribut e, if defined, and from it s t ype object . T he result ing list is not necessarily
complet e and may be inaccurat e when t he object has a custom __getattr__() .

T he default dir() mechanism behaves different ly wit h different t ypes of object s, as it at t empt s to
produce t he most relevant , rat her t han complet e, informat ion:

If t he object is a module object , t he list cont ains t he names of t he module’s at t ribut es.
If t he object is a t ype or class object , t he list cont ains t he names of it s at t ribut es, and recursively
of t he at t ribut es of it s bases.
Ot herwise, t he list cont ains t he object ’s at t ribut es’ names, t he names of it s class’s at t ribut es, and
recursively of t he at t ribut es of it s class’s base classes.

T he result ing list is sort ed alphabet ically. For example:

>>> import struct >>>


>>> dir() # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__', '__package__',
'_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

Note: Because dir() is supplied primarily as a convenience for use at an int eract ive prompt , it
t ries to supply an int erest ing set of names more t han it t ries to supply a rigorously or consist ent ly
defined set of names, and it s det ailed behavior may change across releases. For example,
met aclass at t ribut es are not in t he result list when t he argument is a class.

divmod(a, b)
Take t wo (non-complex) numbers as argument s and ret urn a pair of numbers consist ing of t heir
quot ient and remainder when using int eger division. Wit h mixed operand t ypes, t he rules for binary
arit hmet ic operators apply. For int egers, t he result is t he same as (a // b, a % b) . For float ing
point numbers t he result is (q, a % b) , where q is usually math.floor(a / b) but may be 1 less
t han t hat . In any case q * b + a % b is very close to a , if a % b is non-zero it has t he same sign as
b, and 0 <= abs(a % b) < abs(b) .

enumerate(iterable, start=0)
Ret urn an enumerat e object . iterable must be a sequence, an it erator, or some ot her object which
support s it erat ion. T he __next__() met hod of t he it erator ret urned by enumerate() ret urns a t uple
cont aining a count (from start which default s to 0) and t he values obt ained from it erat ing 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)


T he argument s are a st ring and opt ional globals and locals. If provided, globals must be a dict ionary. If
provided, locals can be any mapping object .

T he expression argument is parsed and evaluat ed as a Pyt hon expression (t echnically speaking, a
condit ion list ) using t he globals and locals dict ionaries as global and local namespace. If t he globals
dict ionary is present and does not cont ain a value for t he key __builtins__ , a reference to t he
dict ionary of t he built -in module builtins is insert ed under t hat key before expression is parsed.
T hat way you can cont rol what built ins are available to t he execut ed code by insert ing your own
__builtins__ dict ionary into globals before passing it to eval() . If t he locals dict ionary is omit t ed it
default s to t he globals dict ionary. If bot h dict ionaries are omit t ed, t he expression is execut ed wit h t he
globals and locals in t he environment where eval() is called. Not e, eval() does not have access to t he
nest ed scopes (non-locals) in t he enclosing environment .

T he ret urn value is t he result of t he evaluat ed expression. Synt ax errors are report ed as except ions.
Example:

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

T his funct ion can also be used to execut e arbit rary code object s (such as t hose creat ed by
compile() ). In t his case, pass a code object inst ead of a st ring. If t he code object has been compiled
wit h 'exec' as t he mode argument , eval() 's ret urn value will be None .
Hint s: dynamic execut ion of st at ement s is support ed by t he exec() funct ion. T he globals() and
locals() funct ions ret urn t he current global and local dict ionary, respect ively, which may be useful
to pass around for use by eval() or exec() .

If t he given source is a st ring, t hen leading and t railing spaces and t abs are st ripped.

See ast.literal_eval() for a funct ion t hat can safely evaluat e st rings wit h expressions
cont aining only lit erals.

Raises an audit ing event exec wit h t he code object as t he argument . Code compilat ion event s may
also be raised.

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


T his funct ion support s dynamic execut ion of Pyt hon code. object must be eit her a st ring or a code
object . If it is a st ring, t he st ring is parsed as a suit e of Pyt hon st at ement s which is t hen execut ed
(unless a synt ax error occurs). [1] If it is a code object , it is simply execut ed. In all cases, t he code
t hat ’s execut ed is expect ed to be valid as file input (see t he sect ion File input in t he Reference
Manual). Be aware t hat t he nonlocal , yield , and return st at ement s may not be used out side of
funct ion definit ions even wit hin t he cont ext of code passed to t he exec() funct ion. T he ret urn value
is None .

In all cases, if t he opt ional part s are omit t ed, t he code is execut ed in t he current scope. If only globals
is provided, it must be a dict ionary (and not a subclass of dict ionary), which will be used for bot h t he
global and t he local variables. If globals and locals are given, t hey are used for t he global and local
variables, respect ively. If provided, locals can be any mapping object . Remember t hat at t he module
level, globals and locals are t he same dict ionary. If exec get s t wo separat e object s as globals and
locals , t he code will be execut ed as if it were embedded in a class definit ion.

If t he globals dict ionary does not cont ain a value for t he key __builtins__ , a reference to t he
dict ionary of t he built -in module builtins is insert ed under t hat key. T hat way you can cont rol what
built ins are available to t he execut ed code by insert ing your own __builtins__ dict ionary into globals
before passing it to exec() .

T he closure argument specifies a closure–a t uple of cellvars. It ’s only valid when t he object is a code
object cont aining free variables. T he lengt h of t he t uple must exact ly mat ch t he number of free
variables referenced by t he code object .

Raises an audit ing event exec wit h t he code object as t he argument . Code compilat ion event s may
also be raised.

Note: T he built -in funct ions globals() and locals() ret urn t he current global and local
dict ionary, respect ively, which may be useful to pass around for use as t he second and t hird
argument to exec() .

Note: T he default locals act as described for funct ion locals() below: modificat ions to t he
default locals dict ionary should not be at t empt ed. Pass an explicit locals dict ionary if you need to
see effect s of t he code on locals aft er funct ion exec() ret urns.

Changed in version 3.11: Added t he closure paramet er.

filter(function, iterable)
Const ruct an it erator from t hose element s of iterable for which function is t rue. iterable may be eit her a
sequence, a cont ainer which support s it erat ion, or an it erator. If function is None , t he ident it y funct ion
is assumed, t hat is, all element s of iterable t hat are false are removed.
Not e t hat filter(function, iterable) is equivalent to t he generator expression (item for
item in iterable if function(item)) if funct ion is not None and (item for item in
iterable if item) if funct ion is None .

See itertools.filterfalse() for t he complement ary funct ion t hat ret urns element s of iterable
for which function is false.

class float(x=0.0)
Ret urn a float ing point number const ruct ed from a number or st ring x.

If t he argument is a st ring, it should cont ain a decimal number, opt ionally preceded by a sign, and
opt ionally embedded in whit espace. T he opt ional sign may be '+' or '-' ; a '+' sign has no effect on
t he value produced. T he argument may also be a st ring represent ing a NaN (not -a-number), or posit ive
or negat ive infinit y. More precisely, t he input must conform to t he floatvalue product ion rule in t he
following grammar, aft er leading and t railing whit espace charact ers are removed:

sign ::= "+" | "-"


infinity ::= "Infinity" | "inf"
nan ::= "nan"
digitpart ::= digit (["_"] digit )*
number ::= [ digitpart ] "." digitpart | digitpart ["."]
exponent ::= ("e" | "E") ["+" | "-"] digitpart
floatnumber ::= number [ exponent ]
floatvalue ::= [ sign ] ( floatnumber | infinity | nan )

Here digit is a Unicode decimal digit (charact er in t he Unicode general cat egory Nd ). Case is not
significant , so, for example, “inf”, “Inf”, “INFINIT Y”, and “iNfINit y” are all accept able spellings for posit ive
infinit y.

Ot herwise, if t he argument is an int eger or a float ing point number, a float ing point number wit h t he
same value (wit hin Pyt hon’s float ing point precision) is ret urned. If t he argument is out side t he range
of a Pyt hon float , an OverflowError will be raised.

For a general Pyt hon object x , float(x) delegat es to x.__float__() . If __float__() is not defined
t hen it falls back to __index__() .

If no argument is given, 0.0 is ret urned.

Examples:

>>> float('+1.23') >>>


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

T he float t ype is described in Numeric Types — int , float , complex.

Changed in version 3.6: Grouping digit s wit h underscores as in code lit erals is allowed.

Changed in version 3.7: x is now a posit ional-only paramet er.

Changed in version 3.8: Falls back to __index__() if __float__() is not defined.


format(value, format_spec='')
Convert a value to a “format t ed” represent at ion, as cont rolled by format_spec . T he int erpret at ion of
format_spec will depend on t he t ype of t he value argument ; however, t here is a st andard format t ing
synt ax t hat is used by most built -in t ypes: Format Specificat ion Mini-Language.

T he default format_spec is an empt y st ring which usually gives t he same effect as calling
str(value) .

A call to format(value, format_spec) is t ranslat ed to type(value).__format__(value,


format_spec) which bypasses t he inst ance dict ionary when searching for t he value’s __format__()
met hod. A TypeError except ion is raised if t he met hod search reaches object and t he format_spec
is non-empt y, or if eit her t he format_spec or t he ret urn value are not st rings.

Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is


not an empt y st ring.

class frozenset(iterable=set())
Ret urn a new frozenset object , opt ionally wit h element s t aken from iterable. frozenset is a built -in
class. See frozenset and Set Types — set , frozenset for document at ion about t his class.

For ot her cont ainers see t he built -in set , list , tuple , and dict classes, as well as t he collections
module.

getattr(object, name)
getattr(object, name, default)
Ret urn t he value of t he named at t ribut e of object. name must be a st ring. If t he st ring is t he name of
one of t he object ’s at t ribut es, t he result is t he value of t hat at t ribut e. For example, getattr(x,
'foobar') is equivalent to x.foobar . If t he named at t ribut e does not exist , default is ret urned if
provided, ot herwise AttributeError is raised. name need not be a Pyt hon ident ifier (see
setattr() ).

Note: Since privat e name mangling happens at compilat ion t ime, one must manually mangle a
privat e at t ribut e’s (at t ribut es wit h t wo leading underscores) name in order to ret rieve it wit h
getattr() .

globals()
Ret urn t he dict ionary implement ing t he current module namespace. For code wit hin funct ions, t his is
set when t he funct ion is defined and remains t he same regardless of where t he funct ion is called.

hasattr(object, name)
T he argument s are an object and a st ring. T he result is True if t he st ring is t he name of one of t he
object ’s at t ribut es, False if not . (T his is implement ed by calling getattr(object, name) and
seeing whet her it raises an AttributeError or not .)

hash(object)
Ret urn t he hash value of t he object (if it has one). Hash values are int egers. T hey are used to quickly
compare dict ionary keys during a dict ionary lookup. Numeric values t hat compare equal have t he
same hash value (even if t hey are of different t ypes, as is t he case for 1 and 1.0).

Note: For object s wit h custom __hash__() met hods, not e t hat hash() t runcat es t he ret urn
value based on t he bit widt h of t he host machine. See __hash__() for det ails.

help()
help(request)
Invoke t he built -in help syst em. (T his funct ion is int ended for int eract ive use.) If no argument is given,
t he int eract ive help syst em st art s on t he int erpret er console. If t he argument is a st ring, t hen t he
st ring is looked up as t he name of a module, funct ion, class, met hod, keyword, or document at ion
topic, and a help page is print ed on t he console. If t he argument is any ot her kind of object , a help page
on t he object is generat ed.

Not e t hat if a slash(/) appears in t he paramet er list of a funct ion when invoking help() , it means t hat
t he paramet ers prior to t he slash are posit ional-only. For more info, see t he FAQ ent ry on posit ional-
only paramet ers.

T his funct ion is added to t he built -in namespace by t he site module.

Changed in version 3.4: Changes to pydoc and inspect mean t hat t he report ed signat ures for
callables are now more comprehensive and consist ent .

hex(x)
Convert an int eger number to a lowercase hexadecimal st ring prefixed wit h “0x”. If x is not a Pyt hon
int object , it has to define an __index__() met hod t hat ret urns an int eger. Some examples:

>>> hex(255) >>>


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

If you want to convert an int eger number to an uppercase or lower hexadecimal st ring wit h prefix or
not , you can use eit her of t he 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')

See also format() for more informat ion.

See also int() for convert ing a hexadecimal st ring to an int eger using a base of 16.

Note: To obt ain a hexadecimal st ring represent at ion for a float , use t he float.hex() met hod.

id(object)
Ret urn t he “ident it y” of an object . T his is an int eger which is guarant eed to be unique and const ant for
t his object during it s lifet ime. Two object s wit h non-overlapping lifet imes may have t he same id()
value.

CPython implementation detail: T his is t he address of t he object in memory.

Raises an audit ing event builtins.id wit h argument id .

input()
input(prompt)
If t he prompt argument is present , it is writ t en to st andard out put wit hout a t railing newline. T he
funct ion t hen reads a line from input , convert s it to a st ring (st ripping a t railing newline), and ret urns
t hat . When EOF is read, EOFError is raised. Example:
>>> s = input('--> ') >>>
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If t he readline module was loaded, t hen input() will use it to provide elaborat e line edit ing and
history feat ures.

Raises an audit ing event builtins.input wit h argument prompt before reading input

Raises an audit ing event builtins.input/result wit h t he result aft er successfully reading input .

class int(x=0)
class int(x, base=10)
Ret urn an int eger object const ruct ed from a number or st ring x, or ret urn 0 if no argument s are given.
If x defines __int__() , int(x) ret urns x.__int__() . If x defines __index__() , it ret urns
x.__index__() . If x defines __trunc__() , it ret urns x.__trunc__() . For float ing point numbers, t his
t runcat es towards zero.

If x is not a number or if base is given, t hen x must be a st ring, bytes , or bytearray inst ance
represent ing an int eger in radix base. Opt ionally, t he st ring can be preceded by + or - (wit h no space in
bet ween), have leading zeros, be surrounded by whit espace, and have single underscores
int erspersed bet ween digit s.

A base-n int eger st ring cont ains digit s, each represent ing a value from 0 to n-1. T he values 0–9 can be
represent ed by any Unicode decimal digit . T he values 10–35 can be represent ed by a to z (or A to Z ).
T he default base is 10. T he allowed bases are 0 and 2–36. Base-2, -8, and -16 st rings can be opt ionally
prefixed wit h 0b / 0B , 0o / 0O , or 0x / 0X , as wit h int eger lit erals in code. For base 0, t he st ring is
int erpret ed in a similar way to an int eger lit eral in code, in t hat t he act ual base is 2, 8, 10, or 16 as
det ermined by t he prefix. Base 0 also disallows leading zeros: int('010', 0) is not legal, while
int('010') and int('010', 8) are.

T he int eger t ype is described in Numeric Types — int , float , complex.

Changed in version 3.4: If base is not an inst ance of int and t he base object has a base.__index__
met hod, t hat met hod is called to obt ain an int eger for t he base. Previous versions used
base.__int__ inst ead of base.__index__ .

Changed in version 3.6: Grouping digit s wit h underscores as in code lit erals is allowed.

Changed in version 3.7: x is now a posit ional-only paramet er.

Changed in version 3.8: Falls back to __index__() if __int__() is not defined.

Changed in version 3.11: T he delegat ion to __trunc__() is deprecat ed.

Changed in version 3.11: int st ring input s and st ring represent at ions can be limit ed to help avoid
denial of service at t acks. A ValueError is raised when t he limit is exceeded while convert ing a st ring
x to an int or when convert ing an int into a st ring would exceed t he limit . See t he int eger st ring
conversion lengt h limit at ion document at ion.

isinstance(object, classinfo)
Ret urn True if t he object argument is an inst ance of t he classinfo argument , or of a (direct , indirect ,
or virt ual) subclass t hereof. If object is not an object of t he given t ype, t he funct ion always ret urns
False . If classinfo is a t uple of t ype object s (or recursively, ot her such t uples) or a Union Type of
mult iple t ypes, ret urn True if object is an inst ance of any of t he t ypes. If classinfo is not a t ype or
t uple of t ypes and such t uples, a TypeError except ion is raised. TypeError may not be raised for an
invalid t ype if an earlier check succeeds.

Changed in version 3.10: classinfo can be a Union Type.

issubclass(class, classinfo)
Ret urn True if class is a subclass (direct , indirect , or virt ual) of classinfo. A class is considered a
subclass of it self. classinfo may be a t uple of class object s (or recursively, ot her such t uples) or a
Union Type, in which case ret urn True if class is a subclass of any ent ry in classinfo. In any ot her
case, a TypeError except ion is raised.

Changed in version 3.10: classinfo can be a Union Type.

iter(object)
iter(object, sentinel)
Ret urn an it erator object . T he first argument is int erpret ed very different ly depending on t he presence
of t he second argument . Wit hout a second argument , object must be a collect ion object which
support s t he it erable protocol (t he __iter__() met hod), or it must support t he sequence protocol
(t he __getitem__() met hod wit h int eger argument s st art ing at 0 ). If it does not support eit her of
t hose protocols, TypeError is raised. If t he second argument , sentinel, is given, t hen object must be a
callable object . T he it erator creat ed in t his case will call object wit h no argument s for each call to it s
__next__() met hod; if t he value ret urned is equal to sentinel, StopIteration will be raised,
ot herwise t he value will be ret urned.

See also It erator Types.

One useful applicat ion of t he second form of iter() is to build a block-reader. For example, reading
fixed-widt h blocks from a binary dat abase file unt il t he 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)
Ret urn t he lengt h (t he number of it ems) of an object . T he argument may be a sequence (such as a
st ring, byt es, t uple, list , or range) or a collect ion (such as a dict ionary, set , or frozen set ).

CPython implementation detail: len raises OverflowError on lengt hs larger t han sys.maxsize ,
such as range(2 ** 100) .

class list
class list(iterable)
Rat her t han being a funct ion, list is act ually a mut able sequence t ype, as document ed in List s and
Sequence Types — list , t uple, range.

locals()
Updat e and ret urn a dict ionary represent ing t he current local symbol t able. Free variables are ret urned
by locals() when it is called in funct ion blocks, but not in class blocks. Not e t hat at t he module level,
locals() and globals() are t he same dict ionary.

Note: T he cont ent s of t his dict ionary should not be modified; changes may not affect t he values
of local and free variables used by t he int erpret er.

map(function, iterable, *iterables)


Ret urn an it erator t hat applies function to every it em of iterable, yielding t he result s. If addit ional
iterables argument s are passed, function must t ake t hat many argument s and is applied to t he it ems
from all it erables in parallel. Wit h mult iple it erables, t he it erator stops when t he short est it erable is
exhaust ed. For cases where t he funct ion input s are already arranged into argument t uples, see
itertools.starmap() .

max(iterable, *, key=None)
max(iterable, *, default, key=None)
max(arg1, arg2, *args, key=None)
Ret urn t he largest it em in an it erable or t he largest of t wo or more argument s.

If one posit ional argument is provided, it should be an it erable. T he largest it em in t he it erable is


ret urned. If t wo or more posit ional argument s are provided, t he largest of t he posit ional argument s is
ret urned.

T here are t wo opt ional keyword-only argument s. T he key argument specifies a one-argument ordering
funct ion like t hat used for list.sort() . T he default argument specifies an object to ret urn if t he
provided it erable is empt y. If t he it erable is empt y and default is not provided, a ValueError is raised.

If mult iple it ems are maximal, t he funct ion ret urns t he first one encount ered. T his is consist ent wit h
ot her sort -st abilit y preserving tools such as sorted(iterable, key=keyfunc,
reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc) .

New in version 3.4: T he default keyword-only argument .

Changed in version 3.8: T he key can be None .

class memoryview(object)
Ret urn a “memory view” object creat ed from t he given argument . See Memory Views for more
informat ion.

min(iterable, *, key=None)
min(iterable, *, default, key=None)
min(arg1, arg2, *args, key=None)
Ret urn t he smallest it em in an it erable or t he smallest of t wo or more argument s.

If one posit ional argument is provided, it should be an it erable. T he smallest it em in t he it erable is


ret urned. If t wo or more posit ional argument s are provided, t he smallest of t he posit ional argument s
is ret urned.

T here are t wo opt ional keyword-only argument s. T he key argument specifies a one-argument ordering
funct ion like t hat used for list.sort() . T he default argument specifies an object to ret urn if t he
provided it erable is empt y. If t he it erable is empt y and default is not provided, a ValueError is raised.

If mult iple it ems are minimal, t he funct ion ret urns t he first one encount ered. T his is consist ent wit h
ot her sort -st abilit y preserving tools such as sorted(iterable, key=keyfunc)[0] and
heapq.nsmallest(1, iterable, key=keyfunc) .

New in version 3.4: T he default keyword-only argument .

Changed in version 3.8: T he key can be None .

next(iterator)
next(iterator, default)
Ret rieve t he next it em from t he it erator by calling it s __next__() met hod. If default is given, it is
ret urned if t he it erator is exhaust ed, ot herwise StopIteration is raised.
class object
Ret urn a new feat ureless object . object is a base for all classes. It has met hods t hat are common to
all inst ances of Pyt hon classes. T his funct ion does not accept any argument s.

Note: object does not have a __dict__ , so you can’t assign arbit rary at t ribut es to an inst ance of
t he object class.

oct(x)
Convert an int eger number to an oct al st ring prefixed wit h “0o”. T he result is a valid Pyt hon expression.
If x is not a Pyt hon int object , it has to define an __index__() met hod t hat ret urns an int eger. For
example:

>>> oct(8) >>>


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

If you want to convert an int eger number to an oct al st ring eit her wit h t he prefix “0o” or not , you can
use eit her of t he following ways.

>>> '%#o' % 10, '%o' % 10 >>>


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

See also format() for more informat ion.

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None,


closefd=True, opener=None)
Open file and ret urn a corresponding file object . If t he file cannot be opened, an OSError is raised. See
Reading and Writ ing Files for more examples of how to use t his funct ion.

file is a pat h-like object giving t he pat hname (absolut e or relat ive to t he current working directory) of
t he file to be opened or an int eger file descriptor of t he file to be wrapped. (If a file descriptor is given, it
is closed when t he ret urned I/O object is closed unless closefd is set to False .)

mode is an opt ional st ring t hat specifies t he mode in which t he file is opened. It default s to 'r' which
means open for reading in t ext mode. Ot her common values are 'w' for writ ing (t runcat ing t he file if it
already exist s), 'x' for exclusive creat ion, and 'a' for appending (which on some Unix syst ems,
means t hat all writ es append to t he end of t he file regardless of t he current seek posit ion). In t ext
mode, if encoding is not specified t he encoding used is plat form-dependent : locale.getencoding()
is called to get t he current locale encoding. (For reading and writ ing raw byt es use binary mode and
leave encoding unspecified.) T he available modes are:

Character Meaning

'r' open for reading (default )

'w' open for writ ing, t runcat ing t he file first

'x' open for exclusive creat ion, failing if t he file already exist s

'a' open for writ ing, appending to t he end of file if it exist s


Character Meaning

'b' binary mode

't' t ext mode (default )

'+' open for updat ing (reading and writ ing)

T he default mode is 'r' (open for reading t ext , a synonym of 'rt' ). Modes 'w+' and 'w+b' open
and t runcat e t he file. Modes 'r+' and 'r+b' open t he file wit h no t runcat ion.

As ment ioned in t he Overview, Pyt hon dist inguishes bet ween binary and t ext I/O. Files opened in binary
mode (including 'b' in t he mode argument ) ret urn cont ent s as bytes object s wit hout any decoding.
In t ext mode (t he default , or when 't' is included in t he mode argument ), t he cont ent s of t he file are
ret urned as str , t he byt es having been first decoded using a plat form-dependent encoding or using
t he specified encoding if given.

Note: Pyt hon doesn’t depend on t he underlying operat ing syst em’s not ion of t ext files; all t he
processing is done by Pyt hon it self, and is t herefore plat form-independent .

buffering is an opt ional int eger used to set t he buffering policy. Pass 0 to swit ch buffering off (only
allowed in binary mode), 1 to select line buffering (only usable in t ext mode), and an int eger > 1 to
indicat e t he size in byt es of a fixed-size chunk buffer. Not e t hat specifying a buffer size t his way
applies for binary buffered I/O, but TextIOWrapper (i.e., files opened wit h mode='r+' ) would have
anot her buffering. To disable buffering in TextIOWrapper , consider using t he write_through flag for
io.TextIOWrapper.reconfigure() . When no buffering argument is given, t he default buffering
policy works as follows:

Binary files are buffered in fixed-size chunks; t he size of t he buffer is chosen using a heurist ic
t rying to det ermine t he underlying device’s “block size” and falling back on
io.DEFAULT_BUFFER_SIZE . On many syst ems, t he buffer will t ypically be 4096 or 8192 byt es long.
“Int eract ive” t ext files (files for which isatty() ret urns True ) use line buffering. Ot her t ext files
use t he policy described above for binary files.

encoding is t he name of t he encoding used to decode or encode t he file. T his should only be used in
t ext mode. T he default encoding is plat form dependent (what ever locale.getencoding() ret urns),
but any t ext encoding support ed by Pyt hon can be used. See t he codecs module for t he list of
support ed encodings.

errors is an opt ional st ring t hat specifies how encoding and decoding errors are to be handled—t his
cannot be used in binary mode. A variet y of st andard error handlers are available (list ed under Error
Handlers), t hough any error handling name t hat has been regist ered wit h codecs.register_error()
is also valid. T he st andard names include:

'strict' to raise a ValueError except ion if t here is an encoding error. T he default value of None
has t he same effect .
'ignore' ignores errors. Not e t hat ignoring encoding errors can lead to dat a loss.
'replace' causes a replacement marker (such as '?' ) to be insert ed where t here is malformed
dat a.
'surrogateescape' will represent any incorrect byt es as low surrogat e code unit s ranging from
U+DC80 to U+DCFF. T hese surrogat e code unit s will t hen be t urned back into t he same byt es when
t he surrogateescape error handler is used when writ ing dat a. T his is useful for processing files in
an unknown encoding.
'xmlcharrefreplace' is only support ed when writ ing to a file. Charact ers not support ed by t he
encoding are replaced wit h t he appropriat e XML charact er reference &#nnn; .
'backslashreplace' replaces malformed dat a by Pyt hon’s backslashed escape sequences.
'namereplace' (also only support ed when writ ing) replaces unsupport ed charact ers wit h
\N{...} escape sequences.

newline det ermines how to parse newline charact ers from t he st ream. It can be None , '' , '\n' , '\r' ,
and '\r\n' . It works as follows:

When reading input from t he st ream, if newline is None , universal newlines mode is enabled. Lines in
t he input can end in '\n' , '\r' , or '\r\n' , and t hese are t ranslat ed into '\n' before being
ret urned to t he caller. If it is '' , universal newlines mode is enabled, but line endings are ret urned to
t he caller unt ranslat ed. If it has any of t he ot her legal values, input lines are only t erminat ed by t he
given st ring, and t he line ending is ret urned to t he caller unt ranslat ed.
When writ ing out put to t he st ream, if newline is None , any '\n' charact ers writ t en are t ranslat ed to
t he syst em default line separator, os.linesep . If newline is '' or '\n' , no t ranslat ion t akes place.
If newline is any of t he ot her legal values, any '\n' charact ers writ t en are t ranslat ed to t he given
st ring.

If closefd is False and a file descriptor rat her t han a filename was given, t he underlying file descriptor
will be kept open when t he file is closed. If a filename is given closefd must be True (t he default );
ot herwise, an error will be raised.

A custom opener can be used by passing a callable as opener. T he underlying file descriptor for t he file
object is t hen obt ained by calling opener wit h (file, flags ). opener must ret urn an open file descriptor
(passing os.open as opener result s in funct ionalit y similar to passing None ).

T he newly creat ed file is non-inherit able.

T he following example uses t he dir_ fd paramet er of t he os.open() funct ion to open a file relat ive to
a given directory:

>>> 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

T he t ype of file object ret urned by t he open() funct ion depends on t he mode. When open() is used
to open a file in a t ext mode ( 'w' , 'r' , 'wt' , 'rt' , et c.), it ret urns a subclass of io.TextIOBase
(specifically io.TextIOWrapper ). When used to open a file in a binary mode wit h buffering, t he
ret urned class is a subclass of io.BufferedIOBase . T he exact class varies: in read binary mode, it
ret urns an io.BufferedReader ; in writ e binary and append binary modes, it ret urns an
io.BufferedWriter , and in read/writ e mode, it ret urns an io.BufferedRandom . When buffering is
disabled, t he raw st ream, a subclass of io.RawIOBase , io.FileIO , is ret urned.

See also t he file handling modules, such as fileinput , io (where open() is declared), os , os.path ,
tempfile , and shutil .

Raises an audit ing event open wit h argument s file , mode , flags .

T he mode and flags argument s may have been modified or inferred from t he original call.

Changed in version 3.3:


T he opener paramet er was added.
T he 'x' mode was added.
IOError used to be raised, it is now an alias of OSError .
FileExistsError is now raised if t he file opened in exclusive creat ion mode ( 'x' ) already exist s.

Changed in version 3.4:

T he file is now non-inherit able.

Changed in version 3.5:

If t he syst em call is int errupt ed and t he signal handler does not raise an except ion, t he funct ion
now ret ries t he syst em call inst ead of raising an InterruptedError except ion (see PEP 475 for
t he rat ionale).
T he 'namereplace' error handler was added.

Changed in version 3.6:

Support added to accept object s implement ing os.PathLike .


On Windows, opening a console buffer may ret urn a subclass of io.RawIOBase ot her t han
io.FileIO .

Changed in version 3.11: T he 'U' mode has been removed.

ord(c)
Given a st ring represent ing one Unicode charact er, ret urn an int eger represent ing t he Unicode code
point of t hat charact er. For example, ord('a') ret urns t he int eger 97 and ord('€') (Euro sign)
ret urns 8364 . T his is t he inverse of chr() .

pow(base, exp, mod=None)


Ret urn base to t he power exp; if mod is present , ret urn base to t he power exp, modulo mod (comput ed
more efficient ly t han pow(base, exp) % mod ). T he t wo-argument form pow(base, exp) is
equivalent to using t he power operator: base**exp .

T he argument s must have numeric t ypes. Wit h mixed operand t ypes, t he coercion rules for binary
arit hmet ic operators apply. For int operands, t he result has t he same t ype as t he operands (aft er
coercion) unless t he second argument is negat ive; in t hat case, all argument s are convert ed to float
and a float result is delivered. For example, pow(10, 2) ret urns 100 , but pow(10, -2) ret urns 0.01 .
For a negat ive base of t ype int or float and a non-int egral exponent , a complex result is delivered.
For example, pow(-9, 0.5) ret urns a value close to 3j .

For int operands base and exp, if mod is present , mod must also be of int eger t ype and mod must be
nonzero. If mod is present and exp is negat ive, base must be relat ively prime to mod. In t hat case,
pow(inv_base, -exp, mod) is ret urned, where inv_base is an inverse to base modulo mod.

Here’s an example of comput ing an inverse for 38 modulo 97 :

>>> pow(38, -1, mod=97) >>>


23
>>> 23 * 38 % 97 == 1
True

Changed in version 3.8: For int operands, t he t hree-argument form of pow now allows t he second
argument to be negat ive, permit t ing comput at ion of modular inverses.

Changed in version 3.8: Allow keyword argument s. Formerly, only posit ional argument s were
support ed.
print(*objects, sep=' ', end='\n', file=None, flush=False)
Print objects to t he t ext st ream file, separat ed by sep and followed by end. sep, end, file, and flush, if
present , must be given as keyword argument s.

All non-keyword argument s are convert ed to st rings like str() does and writ t en to t he st ream,
separat ed by sep and followed by end. Bot h sep and end must be st rings; t hey can also be None , which
means to use t he default values. If no objects are given, print() will just writ e end.

T he file argument must be an object wit h a write(string) met hod; if it is not present or None ,
sys.stdout will be used. Since print ed argument s are convert ed to t ext st rings, print() cannot be
used wit h binary mode file object s. For t hese, use file.write(...) inst ead.

Whet her t he out put is buffered is usually det ermined by file, but if t he flush keyword argument is t rue,
t he st ream is forcibly flushed.

Changed in version 3.3: Added t he flush keyword argument .

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


Ret urn a propert y at t ribut e.

fget is a funct ion for get t ing an at t ribut e value. fset is a funct ion for set t ing an at t ribut e value. fdel is a
funct ion for delet ing an at t ribut e value. And doc creat es a docst ring for t he at t ribut e.

A t ypical use is to define a managed at t ribut e 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.")

If c is an inst ance of C , c.x will invoke t he get t er, c.x = value will invoke t he set t er, and del c.x
t he delet er.

If given, doc will be t he docst ring of t he propert y at t ribut e. Ot herwise, t he propert y will copy fget’s
docst ring (if it exist s). T his makes it possible to creat e read-only propert ies 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

T he @property decorator t urns t he voltage() met hod into a “get t er” for a read-only at t ribut e wit h
t he same name, and it set s t he docst ring for voltage to “Get t he current volt age.”
A propert y object has getter , setter , and deleter met hods usable as decorators t hat creat e a
copy of t he propert y wit h t he corresponding accessor funct ion set to t he decorat ed funct ion. T his is
best explained wit h an example:

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

T his code is exact ly equivalent to t he first example. Be sure to give t he addit ional funct ions t he same
name as t he original propert y ( x in t his case.)

T he ret urned propert y object also has t he at t ribut es fget , fset , and fdel corresponding to t he
const ructor argument s.

Changed in version 3.5: T he docst rings of propert y object s are now writ eable.

class range(stop)
class range(start, stop, step=1)
Rat her t han being a funct ion, range is act ually an immut able sequence t ype, as document ed in
Ranges and Sequence Types — list , t uple, range.

repr(object)
Ret urn a st ring cont aining a print able represent at ion of an object . For many t ypes, t his funct ion
makes an at t empt to ret urn a st ring t hat would yield an object wit h t he same value when passed to
eval() ; ot herwise, t he represent at ion is a st ring enclosed in angle bracket s t hat cont ains t he name
of t he t ype of t he object toget her wit h addit ional informat ion oft en including t he name and address
of t he object . A class can cont rol what t his funct ion ret urns for it s inst ances by defining a
__repr__() met hod. If sys.displayhook() is not accessible, t his funct ion will raise RuntimeError .

reversed(seq)
Ret urn a reverse it erator. seq must be an object which has a __reversed__() met hod or support s
t he sequence protocol (t he __len__() met hod and t he __getitem__() met hod wit h int eger
argument s st art ing at 0 ).

round(number, ndigits=None)
Ret urn number rounded to ndigits precision aft er t he decimal point . If ndigits is omit t ed or is None , it
ret urns t he nearest int eger to it s input .

For t he built -in t ypes support ing round() , values are rounded to t he closest mult iple of 10 to t he
power minus ndigits ; if t wo mult iples are equally close, rounding is done toward t he even choice (so,
for example, bot h round(0.5) and round(-0.5) are 0 , and round(1.5) is 2 ). Any int eger value is
valid for ndigits (posit ive, zero, or negat ive). T he ret urn value is an int eger if ndigits is omit t ed or None .
Ot herwise, t he ret urn value has t he same t ype as number.
For a general Pyt hon object number , round delegat es to number.__round__ .

Note: T he behavior of round() for float s can be surprising: for example, round(2.675, 2) gives
2.67 inst ead of t he expect ed 2.68 . T his is not a bug: it ’s a result of t he fact t hat most decimal
fract ions can’t be represent ed exact ly as a float . See Float ing Point Arit hmet ic: Issues and
Limit at ions for more informat ion.

class set
class set(iterable)
Ret urn a new set object , opt ionally wit h element s t aken from iterable. set is a built -in class. See set
and Set Types — set , frozenset for document at ion about t his class.

For ot her cont ainers see t he built -in frozenset , list , tuple , and dict classes, as well as t he
collections module.

setattr(object, name, value)


T his is t he count erpart of getattr() . T he argument s are an object , a st ring, and an arbit rary value.
T he st ring may name an exist ing at t ribut e or a new at t ribut e. T he funct ion assigns t he value to t he
at t ribut e, provided t he object allows it . For example, setattr(x, 'foobar', 123) is equivalent to
x.foobar = 123 .

name need not be a Pyt hon ident ifier as defined in Ident ifiers and keywords unless t he object chooses
to enforce t hat , for example in a custom __getattribute__() or via __slots__ . An at t ribut e whose
name is not an ident ifier will not be accessible using t he dot not at ion, but is accessible t hrough
getattr() et c..

Note: Since privat e name mangling happens at compilat ion t ime, one must manually mangle a
privat e at t ribut e’s (at t ribut es wit h t wo leading underscores) name in order to set it wit h
setattr() .

class slice(stop)
class slice(start, stop, step=1)
Ret urn a slice object represent ing t he set of indices specified by range(start, stop, step) . T he
start and step argument s default to None . Slice object s have read-only dat a at t ribut es start , stop ,
and step which merely ret urn t he argument values (or t heir default ). T hey have no ot her explicit
funct ionalit y; however, t hey are used by NumPy and ot her t hird-part y packages. Slice object s are also
generat ed when ext ended indexing synt ax is used. For example: a[start:stop:step] or
a[start:stop, i] . See itertools.islice() for an alt ernat e version t hat ret urns an it erator.

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


Ret urn a new sort ed list from t he it ems in iterable.

Has t wo opt ional argument s which must be specified as keyword argument s.

key specifies a funct ion of one argument t hat is used to ext ract a comparison key from each element
in iterable (for example, key=str.lower ). T he default value is None (compare t he element s direct ly).

reverse is a boolean value. If set to True , t hen t he list element s are sort ed as if each comparison were
reversed.

Use functools.cmp_to_key() to convert an old-st yle cmp funct ion to a key funct ion.

T he built -in sorted() funct ion is guarant eed to be st able. A sort is st able if it guarant ees not to
change t he relat ive order of element s t hat compare equal — t his is helpful for sort ing in mult iple
passes (for example, sort by depart ment , t hen by salary grade).

T he sort algorit hm uses only < comparisons bet ween it ems. While defining an __lt__() met hod will
suffice for sort ing, PEP 8 recommends t hat all six rich comparisons be implement ed. T his will help
avoid bugs when using t he same dat a wit h ot her ordering tools such as max() t hat rely on a different
underlying met hod. Implement ing all six comparisons also helps avoid confusion for mixed t ype
comparisons which can call reflect ed t he __gt__() met hod.

For sort ing examples and a brief sort ing t utorial, see Sort ing HOW T O.

@staticmethod
Transform a met hod into a st at ic met hod.

A st at ic met hod does not receive an implicit first argument . To declare a st at ic met hod, use t his
idiom:

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

T he @staticmethod form is a funct ion decorator – see Funct ion definit ions for det ails.

A st at ic met hod can be called eit her on t he class (such as C.f() ) or on an inst ance (such as
C().f() ). Moreover, t hey can be called as regular funct ions (such as f() ).

St at ic met hods in Pyt hon are similar to t hose found in Java or C++. Also, see classmethod() for a
variant t hat is useful for creat ing alt ernat e class const ructors.

Like all decorators, it is also possible to call staticmethod as a regular funct ion and do somet hing
wit h it s result . T his is needed in some cases where you need a reference to a funct ion from a class
body and you want to avoid t he automat ic t ransformat ion to inst ance met hod. For t hese cases, use
t his idiom:

def regular_function():
...

class C:
method = staticmethod(regular_function)

For more informat ion on st at ic met hods, see T he st andard t ype hierarchy.

Changed in version 3.10: St at ic met hods now inherit t he met hod at t ribut es ( __module__ , __name__ ,
__qualname__ , __doc__ and __annotations__ ), have a new __wrapped__ at t ribut e, and are now
callable as regular funct ions.

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
Ret urn a str version of object. See str() for det ails.

str is t he built -in st ring class. For general informat ion about st rings, see Text Sequence Type — st r.

sum(iterable, /, start=0)
Sums start and t he it ems of an iterable from left to right and ret urns t he tot al. T he iterable’s it ems are
normally numbers, and t he st art value is not allowed to be a st ring.

For some use cases, t here are good alt ernat ives to sum() . T he preferred, fast way to concat enat e a
sequence of st rings is by calling ''.join(sequence) . To add float ing point values wit h ext ended
precision, see math.fsum() . To concat enat e a series of it erables, consider using
itertools.chain() .

Changed in version 3.8: T he start paramet er can be specified as a keyword argument .

class super
class super(type, object_or_type=None)
Ret urn a proxy object t hat delegat es met hod calls to a parent or sibling class of type. T his is useful for
accessing inherit ed met hods t hat have been overridden in a class.

T he object_or_type det ermines t he met hod resolut ion order to be searched. T he search st art s from
t he class right aft er t he type.

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

T he __mro__ at t ribut e of t he object_or_type list s t he met hod resolut ion search order used by bot h
getattr() and super() . T he at t ribut e is dynamic and can change whenever t he inherit ance
hierarchy is updat ed.

If t he second argument is omit t ed, t he super object ret urned is unbound. If t he second argument is an
object , isinstance(obj, type) must be t rue. If t he second argument is a t ype,
issubclass(type2, type) must be t rue (t his is useful for classmet hods).

T here are t wo t ypical use cases for super. In a class hierarchy wit h single inherit ance, super can be
used to refer to parent classes wit hout naming t hem explicit ly, t hus making t he code more
maint ainable. T his use closely parallels t he use of super in ot her programming languages.

T he second use case is to support cooperat ive mult iple inherit ance in a dynamic execut ion
environment . T his use case is unique to Pyt hon and is not found in st at ically compiled languages or
languages t hat only support single inherit ance. T his makes it possible to implement “diamond
diagrams” where mult iple base classes implement t he same met hod. Good design dict at es t hat such
implement at ions have t he same calling signat ure in every case (because t he order of calls is
det ermined at runt ime, because t hat order adapt s to changes in t he class hierarchy, and because
t hat order can include sibling classes t hat are unknown prior to runt ime).

For bot h use cases, a t ypical superclass call looks like t his:

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

In addit ion to met hod lookups, super() also works for at t ribut e lookups. One possible use case for
t his is calling descriptors in a parent or sibling class.

Not e t hat super() is implement ed as part of t he binding process for explicit dot t ed at t ribut e lookups
such as super().__getitem__(name) . It does so by implement ing it s own __getattribute__()
met hod for searching classes in a predict able order t hat support s cooperat ive mult iple inherit ance.
Accordingly, super() is undefined for implicit lookups using st at ement s or operators such as
super()[name] .

Also not e t hat , aside from t he zero argument form, super() is not limit ed to use inside met hods. T he
t wo argument form specifies t he argument s exact ly and makes t he appropriat e references. T he zero
argument form only works inside a class definit ion, as t he compiler fills in t he necessary det ails to
correct ly ret rieve t he class being defined, as well as accessing t he current inst ance for ordinary
met hods.

For pract ical suggest ions on how to design cooperat ive classes using super() , see guide to using
super().

class tuple
class tuple(iterable)
Rat her t han being a funct ion, tuple is act ually an immut able sequence t ype, as document ed in
Tuples and Sequence Types — list , t uple, range.

class type(object)
class type(name, bases, dict, **kwds)
Wit h one argument , ret urn t he t ype of an object. T he ret urn value is a t ype object and generally t he
same object as ret urned by object.__class__ .

T he isinstance() built -in funct ion is recommended for t est ing t he t ype of an object , because it
t akes subclasses into account .

Wit h t hree argument s, ret urn a new t ype object . T his is essent ially a dynamic form of t he class
st at ement . T he name st ring is t he class name and becomes t he __name__ at t ribut e. T he bases t uple
cont ains t he base classes and becomes t he __bases__ at t ribut e; if empt y, object , t he ult imat e
base of all classes, is added. T he dict dict ionary cont ains at t ribut e and met hod definit ions for t he
class body; it may be copied or wrapped before becoming t he __dict__ at t ribut e. T he following t wo
st at ement s creat e ident ical type object s:

>>> class X: >>>


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

See also Type Object s.

Keyword argument s provided to t he t hree argument form are passed to t he appropriat e met aclass
machinery (usually __init_subclass__() ) in t he same way t hat keywords in a class definit ion
(besides metaclass ) would.

See also Customizing class creat ion.

Changed in version 3.6: Subclasses of type which don’t override type.__new__ may no longer use
t he one-argument form to get t he t ype of an object .

vars()
vars(object)
Ret urn t he __dict__ at t ribut e for a module, class, inst ance, or any ot her object wit h a __dict__
at t ribut e.

Object s such as modules and inst ances have an updat eable __dict__ at t ribut e; however, ot her
object s may have writ e rest rict ions on t heir __dict__ at t ribut es (for example, classes use a
types.MappingProxyType to prevent direct dict ionary updat es).

Wit hout an argument , vars() act s like locals() . Not e, t he locals dict ionary is only useful for reads
since updat es to t he locals dict ionary are ignored.

A TypeError except ion is raised if an object is specified but it doesn’t have a __dict__ at t ribut e (for
example, if it s class defines t he __slots__ at t ribut e).
zip(*iterables, strict=False)
It erat e over several it erables in parallel, producing t uples wit h an it em from each one.

Example:

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

More formally: zip() ret urns an it erator of t uples, where t he i-t h t uple cont ains t he i-t h element from
each of t he argument it erables.

Anot her way to t hink of zip() is t hat it t urns rows into columns, and columns into rows. T his is
similar to t ransposing a mat rix.

zip() is lazy: T he element s won’t be processed unt il t he it erable is it erat ed on, e.g. by a for loop or
by wrapping in a list .

One t hing to consider is t hat t he it erables passed to zip() could have different lengt hs; somet imes
by design, and somet imes because of a bug in t he code t hat prepared t hese it erables. Pyt hon offers
t hree different approaches to dealing wit h t his issue:

By default , zip() stops when t he short est it erable is exhaust ed. It will ignore t he remaining it ems
in t he longer it erables, cut t ing off t he result to t he lengt h of t he short est it erable:

>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'])) >>>


[(0, 'fee'), (1, 'fi'), (2, 'fo')]

zip() is oft en used in cases where t he it erables are assumed to be of equal lengt h. In such cases,
it ’s recommended to use t he strict=True opt ion. It s out put is t he same as regular zip() :

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


[('a', 1), ('b', 2), ('c', 3)]

Unlike t he default behavior, it raises a ValueError if one it erable is exhaust ed before t he ot hers:

>>> 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

Wit hout t he strict=True argument , any bug t hat result s in it erables of different lengt hs will be
silenced, possibly manifest ing as a hard-to-find bug in anot her part of t he program.

Short er it erables can be padded wit h a const ant value to make all t he it erables have t he same
lengt h. T his is done by itertools.zip_longest() .

Edge cases: Wit h a single it erable argument , zip() ret urns an it erator of 1-t uples. Wit h no argument s,
it ret urns an empt y it erator.
T ips and t ricks:

T he left -to-right evaluat ion order of t he it erables is guarant eed. T his makes possible an idiom for
clust ering a dat a series into n-lengt h groups using zip(*[iter(s)]*n, strict=True) . T his
repeat s t he same it erator n t imes so t hat each out put t uple has t he result of n calls to t he it erator.
T his has t he effect of dividing t he input into n-lengt h chunks.

zip() in conjunct ion wit h t he * 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

Changed in version 3.10: Added t he strict argument .

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


Note: T his is an advanced funct ion t hat is not needed in everyday Pyt hon programming, unlike
importlib.import_module() .

T his funct ion is invoked by t he import st at ement . It can be replaced (by import ing t he builtins
module and assigning to builtins.__import__ ) in order to change semant ics of t he import
st at ement , but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP
302) to at t ain t he same goals and does not cause issues wit h code which assumes t he default
import implement at ion is in use. Direct use of __import__() is also discouraged in favor of
importlib.import_module() .

T he funct ion import s t he module name, pot ent ially using t he given globals and locals to det ermine
how to int erpret t he name in a package cont ext . T he fromlist gives t he names of object s or
submodules t hat should be import ed from t he module given by name. T he st andard implement at ion
does not use it s locals argument at all and uses it s globals only to det ermine t he package cont ext of
t he import st at ement .

level specifies whet her to use absolut e or relat ive import s. 0 (t he default ) means only perform
absolut e import s. Posit ive values for level indicat e t he number of parent directories to search relat ive
to t he directory of t he module calling __import__() (see PEP 328 for t he det ails).

When t he name variable is of t he form package.module , normally, t he top-level package (t he name up


t ill t he first dot ) is ret urned, not t he module named by name. However, when a non-empt y fromlist
argument is given, t he module named by name is ret urned.

For example, t he st at ement import spam result s in byt ecode resembling t he following code:

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

T he st at ement import spam.ham result s in t his call:

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

Not e how __import__() ret urns t he toplevel module here because t his is t he object t hat is bound to
a name by t he import st at ement .

On t he ot her hand, t he st at ement from spam.ham import eggs, sausage as saus result s in
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

Here, t he spam.ham module is ret urned from __import__() . From t his object , t he names to import
are ret rieved and assigned to t heir respect ive names.

If you simply want to import a module (pot ent ially wit hin a package) by name, use
importlib.import_module() .

Changed in version 3.3: Negat ive values for level are no longer support ed (which also changes t he
default value to 0).

Changed in version 3.9: When t he command line opt ions -E or -I are being used, t he environment
variable PYTHONCASEOK is now ignored.

Footnotes

[1] Not e t hat t he parser only accept s t he Unix-st yle end of line convent ion. If you are reading t he code
from a file, make sure to use newline conversion mode to convert Windows or Mac-st yle newlines.

You might also like