2.Built-in Functions¶
The Python interpreter has a number of functions built into it that are alwaysavailable. They are listed here in alphabetical order.
Built-in Functions | ||||
---|---|---|---|---|
In addition, there are other four built-in functions that are no longerconsidered essential:apply()
,buffer()
,coerce()
, andintern()
. They are documented in theNon-essential Built-in Functionssection.
abs
(x)¶Return the absolute value of a number. The argument may be a plain or longinteger or a floating point number. If the argument is a complex number, itsmagnitude is returned.
all
(iterable)¶Return
True
if all elements of theiterable are true (or if the iterableis empty). Equivalent to:defall(iterable):forelementiniterable:ifnotelement:returnFalsereturnTrue
New in version 2.5.
any
(iterable)¶Return
True
if any element of theiterable is true. If the iterableis empty, returnFalse
. Equivalent to:defany(iterable):forelementiniterable:ifelement:returnTruereturnFalse
New in version 2.5.
basestring
()¶This abstract type is the superclass for
str
andunicode
. Itcannot be called or instantiated, but it can be used to test whether an objectis an instance ofstr
orunicode
.isinstance(obj,basestring)
is equivalent toisinstance(obj,(str,unicode))
.New in version 2.3.
bin
(x)¶Convert an integer number to a binary string. The result is a valid Pythonexpression. Ifx is not a Python
int
object, it has to define an__index__()
method that returns an integer.New in version 2.6.
- class
bool
([x])¶ Return a Boolean value, i.e. one of
True
orFalse
.x is convertedusing the standard truth testing procedure. Ifx is false or omitted, thisreturnsFalse
; otherwise it returnsTrue
.bool
isalso a class, which is a subclass ofint
. Classbool
cannotbe subclassed further. Its only instances areFalse
andTrue
.New in version 2.2.1.
Changed in version 2.3:If no argument is given, this function returns
False
.
- class
bytearray
([source[,encoding[,errors]]])¶ Return a new array of bytes. The
bytearray
class is a mutablesequence of integers in the range 0 <= x < 256. It has most of the usualmethods of mutable sequences, described inMutable Sequence Types, as wellas most methods that thestr
type has, seeString Methods.The optionalsource parameter can be used to initialize the array in a fewdifferent ways:
If it isunicode, you must also give theencoding (and optionally,errors) parameters;
bytearray()
then converts the unicode tobytes usingunicode.encode()
.If it is aninteger, the array will have that size and will beinitialized with null bytes.
If it is an object conforming to thebuffer interface, a read-only bufferof the object will be used to initialize the bytes array.
If it is aniterable, it must be an iterable of integers in the range
0<=x<256
, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
New in version 2.6.
callable
(object)¶Return
True
if theobject argument appears callable,False
if not. If thisreturns true, it is still possible that a call fails, but if it is false,callingobject will never succeed. Note that classes are callable (calling aclass returns a new instance); class instances are callable if they have a__call__()
method.
chr
(i)¶Return a string of one character whose ASCII code is the integeri. Forexample,
chr(97)
returns the string'a'
. This is the inverse oford()
. The argument must be in the range [0..255], inclusive;ValueError
will be raised ifi is outside that range. Seealsounichr()
.
classmethod
(function)¶Return a class method forfunction.
A class method receives the class as implicit first argument, just like aninstance method receives the instance. To declare a class method, use thisidiom:
classC(object):@classmethoddeff(cls,arg1,arg2,...):...
The
@classmethod
form is a functiondecorator – seeFunction definitions for details.A class method can be called either on the class (such as
C.f()
) or on an instance (suchasC().f()
). The instance is ignored except for its class. If a classmethod is called for a derived class, the derived class object is passed as theimplied first argument.Class methods are different than C++ or Java static methods. If you want those,see
staticmethod()
.For more information on class methods, seeThe standard type hierarchy.
New in version 2.2.
Changed in version 2.4:Function decorator syntax added.
cmp
(x,y)¶Compare the two objectsx andy and return an integer according to theoutcome. The return value is negative if
x<y
, zero ifx==y
andstrictly positive ifx>y
.
compile
(source,filename,mode[,flags[,dont_inherit]])¶Compile thesource into a code or AST object. Code objects can be executedby an
exec
statement or evaluated by a call toeval()
.source can either be a Unicode string, aLatin-1 encoded string or anAST object.Refer to theast
module documentation for information on how to workwith AST objects.Thefilename argument should give the file from which the code was read;pass some recognizable value if it wasn’t read from a file (
'<string>'
iscommonly used).Themode argument specifies what kind of code must be compiled; it can be
'exec'
ifsource consists of a sequence of statements,'eval'
if itconsists of a single expression, or'single'
if it consists of a singleinteractive statement (in the latter case, expression statements thatevaluate to something other thanNone
will be printed).The optional argumentsflags anddont_inherit control which futurestatements (seePEP 236) affect the compilation ofsource. If neitheris present (or both are zero) the code is compiled with those futurestatements that are in effect in the code that is calling
compile()
. If theflags argument is given anddont_inherit is not (or is zero) then thefuture statements specified by theflags argument are used in addition tothose that would be used anyway. Ifdont_inherit is a non-zero integer thentheflags argument is it – the future statements in effect around the callto compile are ignored.Future statements are specified by bits which can be bitwise ORed together tospecify multiple statements. The bitfield required to specify a given featurecan be found as the
compiler_flag
attribute onthe_Feature
instance in the__future__
module.This function raises
SyntaxError
if the compiled source is invalid,andTypeError
if the source contains null bytes.If you want to parse Python code into its AST representation, see
ast.parse()
.Note
When compiling a string with multi-line code in
'single'
or'eval'
mode, input must be terminated by at least one newlinecharacter. This is to facilitate detection of incomplete and completestatements in thecode
module.Warning
It is possible to crash the Python interpreter with asufficiently large/complex string when compiling to an ASTobject due to stack depth limitations in Python’s AST compiler.
Changed in version 2.3:Theflags anddont_inherit arguments were added.
Changed in version 2.6:Support for compiling AST objects.
Changed in version 2.7:Allowed use of Windows and Mac newlines. Also input in
'exec'
modedoes not have to end in a newline anymore.
- class
complex
([real[,imag]])¶ Return a complex number with the valuereal +imag*1j or convert a string ornumber to a complex number. If the first parameter is a string, it will beinterpreted as a complex number and the function must be called without a secondparameter. The second parameter can never be a string. Each argument may be anynumeric type (including complex). Ifimag is omitted, it defaults to zero andthe function serves as a numeric conversion function like
int()
,long()
andfloat()
. If both arguments are omitted, returns0j
.Note
When converting from a string, the string must not contain whitespacearound the central
+
or-
operator. For example,complex('1+2j')
is fine, butcomplex('1+2j')
raisesValueError
.The complex type is described inNumeric Types — int, float, long, complex.
delattr
(object,name)¶This is a relative of
setattr()
. The arguments are an object and astring. The string must be the name of one of the object’s attributes. Thefunction deletes the named attribute, provided the object allows it. Forexample,delattr(x,'foobar')
is equivalent todelx.foobar
.
- class
dict
(**kwarg) - class
dict
(mapping,**kwarg) - class
dict
(iterable,**kwarg) Create a new dictionary. The
dict
object is the dictionary class.Seedict
andMapping Types — dict for documentation about this class.For other containers see the built-in
list
,set
, andtuple
classes, as well as thecollections
module.
dir
([object])¶Without arguments, return the list of names in the current local scope. With anargument, attempt to return a list of valid attributes for that object.
If the object has a method named
__dir__()
, this method will be called andmust return the list of attributes. This allows objects that implement a custom__getattr__()
or__getattribute__()
function to customize the waydir()
reports their attributes.If the object does not provide
__dir__()
, the function tries its best togather information from the object’s__dict__
attribute, if defined, andfrom its type object. The resulting list is not necessarily complete, and maybe inaccurate when the object has a custom__getattr__()
.The default
dir()
mechanism behaves differently with different types ofobjects, 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’sattributes.
If the object is a type or class object, the list contains the names of itsattributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of itsclass’s attributes, and recursively of the attributes of its class’s baseclasses.
The resulting list is sorted alphabetically. For example:
>>>importstruct>>>dir()# show the names in the module namespace['__builtins__', '__doc__', '__name__', 'struct']>>>dir(struct)# show the names in the struct module['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']>>>classShape(object): def __dir__(self): return ['area', 'perimeter', 'location']>>>s=Shape()>>>dir(s)['area', 'perimeter', 'location']
Note
Because
dir()
is supplied primarily as a convenience for use at aninteractive prompt, it tries to supply an interesting set of names more than ittries to supply a rigorously or consistently defined set of names, and itsdetailed behavior may change across releases. For example, metaclass attributesare 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 numbersconsisting of their quotient and remainder when using long division. With mixedoperand types, the rules for binary arithmetic operators apply. For plain andlong integers, the result is the same as
(a//b,a%b)
. For floating pointnumbers the result is(q,a%b)
, whereq is usuallymath.floor(a/b)
but may be 1 less than that. In any caseq*b+a%b
is very close toa, ifa%b
is non-zero it has the same sign asb, and0<=abs(a%b)<abs(b)
.Changed in version 2.3:Using
divmod()
with complex numbers is deprecated.
enumerate
(sequence,start=0)¶Return an enumerate object.sequence must be a sequence, aniterator, or some other object which supports iteration. The
next()
method of the iterator returned byenumerate()
returns atuple containing a count (fromstart which defaults to 0) and thevalues obtained from iterating oversequence:>>>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:
defenumerate(sequence,start=0):n=startforeleminsequence:yieldn,elemn+=1
New in version 2.3.
Changed in version 2.6:Thestart parameter was added.
eval
(expression[,globals[,locals]])¶The arguments are a Unicode orLatin-1 encoded string and optionalglobals and locals. If provided,globals must be a dictionary.If provided,locals can be any mapping object.
Changed in version 2.4:formerlylocals was required to be a dictionary.
Theexpression argument is parsed and evaluated as a Python expression(technically speaking, a condition list) using theglobals andlocalsdictionaries as global and local namespace. If theglobals dictionary ispresent and lacks ‘__builtins__’, the current globals are copied intoglobalsbeforeexpression is parsed. This means thatexpression normally has fullaccess to the standard
__builtin__
module and restricted environments arepropagated. If thelocals dictionary is omitted it defaults to theglobalsdictionary. If both dictionaries are omitted, the expression is executed in theenvironment whereeval()
is called. The return value is the result ofthe evaluated expression. Syntax errors are reported as exceptions. Example:>>>x=1>>>printeval('x+1')2
This function can also be used to execute arbitrary code objects (such asthose created by
compile()
). In this case pass a code object insteadof a string. If the code object has been compiled with'exec'
as themode argument,eval()
’s return value will beNone
.Hints: dynamic execution of statements is supported by the
exec
statement. Execution of statements from a file is supported by theexecfile()
function. Theglobals()
andlocals()
functionsreturns the current global and local dictionary, respectively, which may beuseful to pass around for use byeval()
orexecfile()
.See
ast.literal_eval()
for a function that can safely evaluate stringswith expressions containing only literals.
execfile
(filename[,globals[,locals]])¶This function is similar to the
exec
statement, but parses a fileinstead of a string. It is different from theimport
statement inthat it does not use the module administration — it reads the fileunconditionally and does not create a new module.1The arguments are a file name and two optional dictionaries. The file is parsedand evaluated as a sequence of Python statements (similarly to a module) usingtheglobals andlocals dictionaries as global and local namespace. Ifprovided,locals can be any mapping object. Remember that at module level,globals and locals are the same dictionary. If two separate objects arepassed asglobals andlocals, the code will be executed as if it wereembedded in a class definition.
Changed in version 2.4:formerlylocals was required to be a dictionary.
If thelocals dictionary is omitted it defaults to theglobals dictionary.If both dictionaries are omitted, the expression is executed in the environmentwhere
execfile()
is called. The return value isNone
.Note
The defaultlocals act as described for function
locals()
below:modifications to the defaultlocals dictionary should not be attempted. Passan explicitlocals dictionary if you need to see effects of the code onlocals after functionexecfile()
returns.execfile()
cannot beused reliably to modify a function’s locals.
file
(name[,mode[,buffering]])¶Constructor function for the
file
type, described further in sectionFile Objects. The constructor’s arguments are the same as thoseof theopen()
built-in function described below.When opening a file, it’s preferable to use
open()
instead of invokingthis constructor directly.file
is more suited to type testing (forexample, writingisinstance(f,file)
).New in version 2.2.
filter
(function,iterable)¶Construct a list from those elements ofiterable for whichfunction returnstrue.iterable may be either a sequence, a container which supportsiteration, or an iterator. Ifiterable is a string or a tuple, the resultalso has that type; otherwise it is always a list. Iffunction is
None
,the identity function is assumed, that is, all elements ofiterable that arefalse are removed.Note that
filter(function,iterable)
is equivalent to[itemforiteminiterableiffunction(item)]
if function is notNone
and[itemforiteminiterableifitem]
if function isNone
.See
itertools.ifilter()
anditertools.ifilterfalse()
for iteratorversions of this function, including a variation that filters for elementswhere thefunction returns false.
- class
float
([x])¶ Return a floating point number constructed from a number or stringx.
If the argument is a string, itmust contain a possibly signed decimal or floating point number, possiblyembedded in whitespace. The argument may also be [+|-]nan or [+|-]inf.Otherwise, the argument may be a plain or long integeror a floating point number, and a floating point number with the same value(within Python’s floating point precision) is returned. If no argument isgiven, returns
0.0
.Note
When passing in a string, values for NaN and Infinity may be returned, dependingon the underlying C library. Float accepts the strings nan, inf and -inf forNaN and positive or negative infinity. The case and a leading + are ignored aswell as a leading - is ignored for NaN. Float always represents NaN and infinityas nan, inf or -inf.
The float type is described inNumeric Types — int, float, long, complex.
format
(value[,format_spec])¶Convert avalue to a “formatted” representation, as controlled byformat_spec. The interpretation offormat_spec will depend on the typeof thevalue argument, however there is a standard formatting syntax thatis used by most built-in types:Format Specification Mini-Language.
Note
format(value,format_spec)
merely callsvalue.__format__(format_spec)
.New in version 2.6.
- class
frozenset
([iterable]) Return a new
frozenset
object, optionally with elements taken fromiterable.frozenset
is a built-in class. Seefrozenset
andSet Types — set, frozenset for documentation about this class.For other containers see the built-in
set
,list
,tuple
, anddict
classes, as well as thecollections
module.New in version 2.4.
getattr
(object,name[,default])¶Return the value of the named attribute ofobject.name must be a string.If the string is the name of one of the object’s attributes, the result is thevalue of that attribute. For example,
getattr(x,'foobar')
is equivalent tox.foobar
. If the named attribute does not exist,default is returned ifprovided, otherwiseAttributeError
is raised.
globals
()¶Return a dictionary representing the current global symbol table. This is alwaysthe dictionary of the current module (inside a function or method, this is themodule where it is defined, not the module from which it is called).
hasattr
(object,name)¶The arguments are an object and a string. The result is
True
if the stringis the name of one of the object’s attributes,False
if not. (This isimplemented by callinggetattr(object,name)
and seeing whether it raises anexception 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 ofdifferent types, as is the case for 1 and 1.0).
help
([object])¶Invoke the built-in help system. (This function is intended for interactiveuse.) If no argument is given, the interactive help system starts on theinterpreter console. If the argument is a string, then the string is looked upas the name of a module, function, class, method, keyword, or documentationtopic, and a help page is printed on the console. If the argument is any otherkind of object, a help page on the object is generated.
This function is added to the built-in namespace by the
site
module.New in version 2.2.
hex
(x)¶Convert an integer number (of any size) to a lowercase hexadecimal stringprefixed with “0x”, for example:
>>>hex(255)'0xff'>>>hex(-42)'-0x2a'>>>hex(1L)'0x1L'
If x is not a Python
int
orlong
object, it has todefine a __hex__() method that returns a string.See also
int()
for converting a hexadecimal string to aninteger using a base of 16.Note
To obtain a hexadecimal string representation for a float, use the
float.hex()
method.Changed in version 2.4:Formerly only returned an unsigned literal.
id
(object)¶Return the “identity” of an object. This is an integer (or long integer) whichis guaranteed to be unique and constant for this object during its lifetime.Two objects with non-overlapping lifetimes may have the same
id()
value.CPython implementation detail: This is the address of the object in memory.
input
([prompt])¶Equivalent to
eval(raw_input(prompt))
.This function does not catch user errors. If the input is not syntacticallyvalid, a
SyntaxError
will be raised. Other exceptions may be raised ifthere is an error during evaluation.If the
readline
module was loaded, theninput()
will use it toprovide elaborate line editing and history features.Consider using the
raw_input()
function for general input from users.
- class
int
(x=0)¶ - class
int
(x,base=10) Return an integer object constructed from a number or stringx, or return
0
if noarguments are given. Ifx is a number, it can be a plain integer, a longinteger, or a floating point number. Ifx is floating point, the conversiontruncates towards zero. If the argument is outside the integer range, thefunction returns a long object instead.Ifx is not a number or ifbase is given, thenx must be a string orUnicode object representing aninteger literal in radixbase. Optionally, the literal can bepreceded by
+
or-
(with no space in between) and surrounded bywhitespace. A base-n literal consists of the digits 0 to n-1, witha
toz
(orA
toZ
) havingvalues 10 to 35. The defaultbase is 10. The allowed values are 0 and 2–36.Base-2, -8, and -16 literals can be optionally prefixed with0b
/0B
,0o
/0O
/0
, or0x
/0X
, as with integer literals in code.Base 0 means to interpret the string exactly as an integer literal, so thatthe actual base is 2, 8, 10, or 16.The integer type is described inNumeric Types — int, float, long, complex.
isinstance
(object,classinfo)¶Return true if theobject argument is an instance of theclassinfo argument,or of a (direct, indirect orvirtual) subclassthereof. Also return true ifclassinfois a type object (new-style class) andobject is an object of that type or ofa (direct, indirect orvirtual) subclassthereof. Ifobject is not a class instance oran object of the given type, the function always returns false.Ifclassinfo is a tuple of class or type objects (or recursively, othersuch tuples), return true ifobject is an instance of any of the classesor types. Ifclassinfo is not a class, type, or tuple of classes, types,and such tuples, a
TypeError
exception is raised.Changed in version 2.2:Support for a tuple of type information was added.
issubclass
(class,classinfo)¶Return true ifclass is a subclass (direct, indirect orvirtual) ofclassinfo. Aclass is considered a subclass of itself.classinfo may be a tuple of classobjects, in which case every entry inclassinfo will be checked. In any othercase, a
TypeError
exception is raised.Changed in version 2.3:Support for a tuple of type information was added.
iter
(o[,sentinel])¶Return aniterator object. The first argument is interpreted very differentlydepending on the presence of the second argument. Without a second argument,omust be a collection object which supports the iteration protocol (the
__iter__()
method), or it must support the sequence protocol (the__getitem__()
method with integer arguments starting at0
). If itdoes not support either of those protocols,TypeError
is raised. If thesecond argument,sentinel, is given, theno must be a callable object. Theiterator created in this case will callo with no arguments for each call toitsnext()
method; if the value returned is equal tosentinel,StopIteration
will be raised, otherwise the value will be returned.One useful application of the second form of
iter()
is to read lines ofa file until a certain line is reached. The following example reads a fileuntil thereadline()
method returns an empty string:withopen('mydata.txt')asfp:forlineiniter(fp.readline,''):process_line(line)
New in version 2.2.
len
(s)¶Return the length (the number of items) of an object. The argument may be asequence (such as a string, bytes, tuple, list, or range) or a collection(such as a dictionary, set, or frozen set).
- class
list
([iterable]) Return a list whose items are the same and in the same order asiterable’sitems.iterable may be either a sequence, a container that supportsiteration, or an iterator object. Ifiterable is already a list, a copy ismade and returned, similar to
iterable[:]
. For instance,list('abc')
returns['a','b','c']
andlist((1,2,3))
returns[1,2,3]
. Ifno argument is given, returns a new empty list,[]
.list
is a mutable sequence type, as documented inSequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built indict
,set
, andtuple
classes, and thecollections
module.
locals
()¶Update and return a dictionary representing the current local symbol table.Free variables are returned by
locals()
when it is called in functionblocks, but not in class blocks.Note
The contents of this dictionary should not be modified; changes may notaffect the values of local and free variables used by the interpreter.
- class
long
(x=0)¶ - class
long
(x,base=10) Return a long integer object constructed from a string or numberx.If the argument is a string, itmust contain a possibly signed number of arbitrary size, possibly embedded inwhitespace. Thebase argument is interpreted in the same way as for
int()
, and may only be given whenx is a string. Otherwise, the argumentmay be a plain or long integer or a floating point number, and a long integerwith the same value is returned. Conversion of floating point numbers tointegers truncates (towards zero). If no arguments are given, returns0L
.The long type is described inNumeric Types — int, float, long, complex.
map
(function,iterable,...)¶Applyfunction to every item ofiterable and return a list of the results.If additionaliterable arguments are passed,function must take that manyarguments and is applied to the items from all iterables in parallel. If oneiterable is shorter than another it is assumed to be extended with
None
items. Iffunction isNone
, the identity function is assumed; if thereare multiple arguments,map()
returns a list consisting of tuplescontaining the corresponding items from all iterables (a kind of transposeoperation). Theiterable arguments may be a sequence or any iterable object;the result is always a list.
max
(iterable[,key])¶max
(arg1,arg2,*args[,key])Return the largest item in an iterable or the largest of two or morearguments.
If one positional argument is provided,iterable must be a non-emptyiterable (such as a non-empty string, tuple or list). The largest itemin the iterable is returned. If two or more positional arguments areprovided, the largest of the positional arguments is returned.
The optionalkey argument specifies a one-argument ordering function like thatused for
list.sort()
. Thekey argument, if supplied, must be in keywordform (for example,max(a,b,c,key=func)
).Changed in version 2.5:Added support for the optionalkey argument.
memoryview
(obj)Return a “memory view” object created from the given argument. Seememoryview type for more information.
min
(iterable[,key])¶min
(arg1,arg2,*args[,key])Return the smallest item in an iterable or the smallest of two or morearguments.
If one positional argument is provided,iterable must be a non-emptyiterable (such as a non-empty string, tuple or list). The smallest itemin the iterable is returned. If two or more positional arguments areprovided, the smallest of the positional arguments is returned.
The optionalkey argument specifies a one-argument ordering function like thatused for
list.sort()
. Thekey argument, if supplied, must be in keywordform (for example,min(a,b,c,key=func)
).Changed in version 2.5:Added support for the optionalkey argument.
next
(iterator[,default])¶Retrieve the next item from theiterator by calling its
next()
method. Ifdefault is given, it is returned if theiterator is exhausted, otherwiseStopIteration
is raised.New in version 2.6.
- class
object
¶ Return a new featureless object.
object
is a base for all new styleclasses. It has the methods that are common to all instances of new styleclasses.New in version 2.2.
Changed in version 2.3:This function does not accept any arguments. Formerly, it accepted arguments butignored them.
oct
(x)¶Convert an integer number (of any size) to an octal string. The result is avalid Python expression.
Changed in version 2.4:Formerly only returned an unsigned literal.
open
(name[,mode[,buffering]])¶Open a file, returning an object of the
file
type described insectionFile Objects. If the file cannot be opened,IOError
is raised. When opening a file, it’s preferable to useopen()
instead of invoking thefile
constructor directly.The first two arguments are the same as for
stdio
’sfopen()
:name is the file name to be opened, andmode is a string indicating howthe file is to be opened.The most commonly-used values ofmode are
'r'
for reading,'w'
forwriting (truncating the file if it already exists), and'a'
for appending(which onsome Unix systems means thatall writes append to the end of thefile regardless of the current seek position). Ifmode is omitted, itdefaults to'r'
. The default is to use text mode, which may convert'\n'
characters to a platform-specific representation on writing and backon reading. Thus, when opening a binary file, you should append'b'
tothemode value to open the file in binary mode, which will improveportability. (Appending'b'
is useful even on systems that don’t treatbinary and text files differently, where it serves as documentation.) See belowfor more possible values ofmode.The optionalbuffering argument specifies the file’s desired buffer size: 0means unbuffered, 1 means line buffered, any other positive value means use abuffer of (approximately) that size (in bytes). A negativebuffering meansto use the system default, which is usually line buffered for tty devices andfully buffered for other files. If omitted, the system default is used.2
Modes
'r+'
,'w+'
and'a+'
open the file for updating (reading and writing);note that'w+'
truncates the file. Append'b'
to the mode to open the file inbinary mode, on systems that differentiate between binary and text files; onsystems that don’t have this distinction, adding the'b'
has no effect.In addition to the standard
fopen()
valuesmode may be'U'
or'rU'
. Python is usually built withuniversal newlines support;supplying'U'
opens the file as a text file, but lines may be terminatedby any of the following: the Unix end-of-line convention'\n'
, theMacintosh convention'\r'
, or the Windows convention'\r\n'
. All ofthese external representations are seen as'\n'
by the Python program.If Python is built without universal newlines support amode with'U'
is the same as normal text mode. Note that file objects so opened also havean attribute callednewlines
which has a value ofNone
(if nonewlines have yet been seen),'\n'
,'\r'
,'\r\n'
, or a tuplecontaining all the newline types seen.Python enforces that the mode, after stripping
'U'
, begins with'r'
,'w'
or'a'
.Python provides many file handling modules including
fileinput
,os
,os.path
,tempfile
, andshutil
.Changed in version 2.5:Restriction on first letter of mode string introduced.
ord
(c)¶Given a string of length one, return an integer representing the Unicode codepoint of the character when the argument is a unicode object, or the value ofthe byte when the argument is an 8-bit string. For example,
ord('a')
returnsthe integer97
,ord(u'\u2020')
returns8224
. This is the inverse ofchr()
for 8-bit strings and ofunichr()
for unicode objects. If aunicode argument is given and Python was built with UCS2 Unicode, then thecharacter’s code point must be in the range [0..65535] inclusive; otherwise thestring length is two, and aTypeError
will be raised.
pow
(x,y[,z])¶Returnx to the powery; ifz is present, returnx to the powery,moduloz (computed more efficiently than
pow(x,y)%z
). The two-argumentformpow(x,y)
is equivalent to using the power operator:x**y
.The arguments must have numeric types. With mixed operand types, the coercionrules for binary arithmetic operators apply. For int and long int operands, theresult has the same type as the operands (after coercion) unless the secondargument is negative; in that case, all arguments are converted to float and afloat result is delivered. For example,
10**2
returns100
, but10**-2
returns0.01
. (This last feature was added in Python 2.2. InPython 2.1 and before, if both arguments were of integer types and the secondargument was negative, an exception was raised.) If the second argument isnegative, the third argument must be omitted. Ifz is present,x andymust be of integer types, andy must be non-negative. (This restriction wasadded in Python 2.2. In Python 2.1 and before, floating 3-argumentpow()
returned platform-dependent results depending on floating-point roundingaccidents.)
print
(*objects,sep=' ',end='\n',file=sys.stdout)¶Printobjects to the streamfile, separated bysep and followed byend.sep,end andfile, if present, must be given as keywordarguments.
All non-keyword arguments are converted to strings like
str()
does andwritten to the stream, separated bysep and followed byend. Bothsepandend must be strings; they can also beNone
, which means to use thedefault values. If noobjects are given,print()
will just writeend.Thefile argument must be an object with a
write(string)
method; if itis not present orNone
,sys.stdout
will be used. Output bufferingis determined byfile. Usefile.flush()
to ensure, for instance,immediate appearance on a screen.Note
This function is not normally available as a built-in since the name
print
is recognized as theprint
statement. To disable thestatement and use theprint()
function, use this future statement atthe top of your module:from__future__importprint_function
New in version 2.6.
- class
property
([fget[,fset[,fdel[,doc]]]])¶ Return a property attribute fornew-style classes (classes thatderive from
object
).fget is a function for getting an attribute value.fset is a functionfor setting an attribute value.fdel is a function for deleting an attributevalue. Anddoc creates a docstring for the attribute.
A typical use is to define a managed attribute
x
:classC(object):def__init__(self):self._x=Nonedefgetx(self):returnself._xdefsetx(self,value):self._x=valuedefdelx(self):delself._xx=property(getx,setx,delx,"I'm the 'x' property.")
Ifc is an instance ofC,
c.x
will invoke the getter,c.x=value
will invoke the setter anddelc.x
the deleter.If given,doc will be the docstring of the property attribute. Otherwise, theproperty will copyfget’s docstring (if it exists). This makes it possible tocreate read-only properties easily using
property()
as adecorator:classParrot(object):def__init__(self):self._voltage=100000@propertydefvoltage(self):"""Get the current voltage."""returnself._voltage
The
@property
decorator turns thevoltage()
method into a “getter”for a read-only attribute with the same name, and it sets the docstring forvoltage to “Get the current voltage.”A property object has
getter
,setter
,anddeleter
methods usable as decorators that create acopy of the property with the corresponding accessor function set to thedecorated function. This is best explained with an example:classC(object):def__init__(self):self._x=None@propertydefx(self):"""I'm the 'x' property."""returnself._x@x.setterdefx(self,value):self._x=value@x.deleterdefx(self):delself._x
This code is exactly equivalent to the first example. Be sure to give theadditional functions the same name as the original property (
x
in thiscase.)The returned property object also has the attributes
fget
,fset
, andfdel
corresponding to the constructor arguments.New in version 2.2.
Changed in version 2.5:Usefget’s docstring if nodoc given.
Changed in version 2.6:The
getter
,setter
, anddeleter
attributes were added.
range
(stop)¶range
(start,stop[,step])This is a versatile function to create lists containing arithmetic progressions.It is most often used in
for
loops. The arguments must be plainintegers. If thestep argument is omitted, it defaults to1
. If thestart argument is omitted, it defaults to0
. The full form returns a listof plain integers[start,start+step,start+2*step,...]
. Ifstepis positive, the last element is the largeststart+i*step
less thanstop; ifstep is negative, the last element is the smalleststart+i*step
greater thanstop.step must not be zero (or elseValueError
is raised). Example:>>>range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>range(1,11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>>range(0,30,5)[0, 5, 10, 15, 20, 25]>>>range(0,10,3)[0, 3, 6, 9]>>>range(0,-10,-1)[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>>range(0)[]>>>range(1,0)[]
raw_input
([prompt])¶If theprompt argument is present, it is written to standard output without atrailing newline. The function then reads a line from input, converts it to astring (stripping a trailing newline), and returns that. When EOF is read,
EOFError
is raised. Example:>>>s=raw_input('--> ')--> Monty Python's Flying Circus>>>s"Monty Python's Flying Circus"
If the
readline
module was loaded, thenraw_input()
will use it toprovide elaborate line editing and history features.
reduce
(function,iterable[,initializer])¶Applyfunction of two arguments cumulatively to the items ofiterable, fromleft to right, so as to reduce the iterable to a single value. For example,
reduce(lambdax,y:x+y,[1,2,3,4,5])
calculates((((1+2)+3)+4)+5)
.The left argument,x, is the accumulated value and the right argument,y, isthe update value from theiterable. If the optionalinitializer is present,it is placed before the items of the iterable in the calculation, and serves asa default when the iterable is empty. Ifinitializer is not given anditerable contains only one item, the first item is returned.Roughly equivalent to:defreduce(function,iterable,initializer=None):it=iter(iterable)ifinitializerisNone:try:initializer=next(it)exceptStopIteration:raiseTypeError('reduce() of empty sequence with no initial value')accum_value=initializerforxinit:accum_value=function(accum_value,x)returnaccum_value
reload
(module)¶Reload a previously importedmodule. The argument must be a module object, soit must have been successfully imported before. This is useful if you haveedited the module source file using an external editor and want to try out thenew version without leaving the Python interpreter. The return value is themodule object (the same as themodule argument).
When
reload(module)
is executed:Python modules’ code is recompiled and the module-level code reexecuted,defining a new set of objects which are bound to names in the module’sdictionary. The
init
function of extension modules is not called a secondtime.As with all other objects in Python the old objects are only reclaimed aftertheir reference counts drop to zero.
The names in the module namespace are updated to point to any new or changedobjects.
Other references to the old objects (such as names external to the module) arenot rebound to refer to the new objects and must be updated in each namespacewhere they occur if that is desired.
There are a number of other caveats:
When a module is reloaded, its dictionary (containing the module’s globalvariables) is retained. Redefinitions of names will override the olddefinitions, so this is generally not a problem. If the new version of a moduledoes not define a name that was defined by the old version, the old definitionremains. This feature can be used to the module’s advantage if it maintains aglobal table or cache of objects — with a
try
statement it can testfor the table’s presence and skip its initialization if desired:try:cacheexceptNameError:cache={}
It is generally not very useful to reload built-in or dynamically loadedmodules. Reloading
sys
,__main__
,builtins
and otherkey modules is not recommended. In many cases extension modules are notdesigned to be initialized more than once, and may fail in arbitrary wayswhen reloaded.If a module imports objects from another module using
from
…import
…, callingreload()
for the other module does notredefine the objects imported from it — one way around this is to re-executethefrom
statement, another is to useimport
and qualifiednames (module.*name*) instead.If a module instantiates instances of a class, reloading the module that definesthe class does not affect the method definitions of the instances — theycontinue to use the old class definition. The same is true for derived classes.
repr
(object)¶Return a string containing a printable representation of an object. This isthe same value yielded by conversions (reverse quotes). It is sometimesuseful to be able to access this operation as an ordinary function. For manytypes, this function makes an attempt to return a string that would yield anobject with the same value when passed to
eval()
, otherwise therepresentation is a string enclosed in angle brackets that contains the nameof the type of the object together with additional information oftenincluding the name and address of the object. A class can control what thisfunction returns for its instances by defining a__repr__()
method.
reversed
(seq)¶Return a reverseiterator.seq must be an object which hasa
__reversed__()
method or supports the sequence protocol (the__len__()
method and the__getitem__()
method with integerarguments starting at0
).New in version 2.4.
Changed in version 2.6:Added the possibility to write a custom
__reversed__()
method.
round
(number[,ndigits])¶Return the floating point valuenumber rounded tondigits digits afterthe decimal point. Ifndigits is omitted, it defaults to zero. The resultis a floating point number. Values are rounded to the closest multiple of10 to the power minusndigits; if two multiples are equally close,rounding is done away from 0 (so, for example,
round(0.5)
is1.0
andround(-0.5)
is-1.0
).Note
The behavior of
round()
for floats can be surprising: for example,round(2.675,2)
gives2.67
instead of the expected2.68
.This is not a bug: it’s a result of the fact that most decimal fractionscan’t be represented exactly as a float. SeeFloating Point Arithmetic: Issues and Limitations formore information.
- class
set
([iterable]) Return a new
set
object, optionally with elements taken fromiterable.set
is a built-in class. Seeset
andSet Types — set, frozenset for documentation about this class.For other containers see the built-in
frozenset
,list
,tuple
, anddict
classes, as well as thecollections
module.New in version 2.4.
setattr
(object,name,value)¶This is the counterpart of
getattr()
. The arguments are an object, astring and an arbitrary value. The string may name an existing attribute or anew attribute. The function assigns the value to the attribute, provided theobject allows it. For example,setattr(x,'foobar',123)
is equivalent tox.foobar=123
.
- class
slice
(stop)¶ - class
slice
(start,stop[,step]) Return aslice object representing the set of indices specified by
range(start,stop,step)
. Thestart andstep arguments default toNone
. Slice objects have read-only data attributesstart
,stop
andstep
which merely return the argumentvalues (or their default). They have no other explicit functionality;however they are used by Numerical Python and other third party extensions.Slice objects are also generated when extended indexing syntax is used. Forexample:a[start:stop:step]
ora[start:stop,i]
. Seeitertools.islice()
for an alternate version that returns an iterator.
sorted
(iterable[,cmp[,key[,reverse]]])¶Return a new sorted list from the items initerable.
The optional argumentscmp,key, andreverse have the same meaning asthose for the
list.sort()
method (described in sectionMutable Sequence Types).cmp specifies a custom comparison function of two arguments (iterableelements) which should return a negative, zero or positive number depending onwhether the first argument is considered smaller than, equal to, or larger thanthe second argument:
cmp=lambdax,y:cmp(x.lower(),y.lower())
. The defaultvalue isNone
.key specifies a function of one argument that is used to extract a comparisonkey from each list element:
key=str.lower
. The default value isNone
(compare the elements directly).reverse is a boolean value. If set to
True
, then the list elements aresorted as if each comparison were reversed.In general, thekey andreverse conversion processes are much fasterthan specifying an equivalentcmp function. This is becausecmp iscalled multiple times for each list element whilekey andreverse toucheach element only once. Use
functools.cmp_to_key()
to convert anold-stylecmp function to akey function.The built-in
sorted()
function is guaranteed to be stable. A sort isstable if it guarantees not to change the relative order of elements thatcompare equal — this is helpful for sorting in multiple passes (forexample, sort by department, then by salary grade).For sorting examples and a brief sorting tutorial, seeSorting HOW TO.
New in version 2.4.
staticmethod
(function)¶Return a static method forfunction.
A static method does not receive an implicit first argument. To declare a staticmethod, use this idiom:
classC(object):@staticmethoddeff(arg1,arg2,...):...
The
@staticmethod
form is a functiondecorator – seeFunction definitions for details.A static method can be called either on the class (such as
C.f()
) or on an instance (suchasC().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 alternateclass constructors.For more information on static methods, seeThe standard type hierarchy.
New in version 2.2.
Changed in version 2.4:Function decorator syntax added.
- class
str
(object='')¶ Return a string containing a nicely printable representation of an object. Forstrings, this returns the string itself. The difference with
repr(object)
is thatstr(object)
does not always attempt to return a string that isacceptable toeval()
; its goal is to return a printable string. If noargument is given, returns the empty string,''
.For more information on strings seeSequence Types — str, unicode, list, tuple, bytearray, buffer, xrange which describes sequencefunctionality (strings are sequences), and also the string-specific methodsdescribed in theString Methods section. To output formatted stringsuse template strings or the
%
operator described in theString Formatting Operations section. In addition see theString Servicessection. See alsounicode()
.
sum
(iterable[,start])¶Sumsstart and the items of aniterable from left to right and returns thetotal.start defaults to
0
. Theiterable’s items are normally numbers,and the start value is not allowed to be a string.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,seemath.fsum()
. To concatenate a series of iterables, consider usingitertools.chain()
.New in version 2.3.
super
(type[,object-or-type])¶Return a proxy object that delegates method calls to a parent or siblingclass oftype. This is useful for accessing inherited methods that havebeen overridden in a class. The search order is same as that used by
getattr()
except that thetype itself is skipped.The
__mro__
attribute of thetype lists the methodresolution search order used by bothgetattr()
andsuper()
. Theattribute is dynamic and can change whenever the inheritance hierarchy isupdated.If the second argument is omitted, the super object returned is unbound. Ifthe second argument is an object,
isinstance(obj,type)
must be true. Ifthe second argument is a type,issubclass(type2,type)
must be true (thisis useful for classmethods).Note
super()
only works fornew-style classes.There are two typical use cases forsuper. In a class hierarchy withsingle inheritance,super can be used to refer to parent classes withoutnaming them explicitly, thus making the code more maintainable. This useclosely parallels the use ofsuper in other programming languages.
The second use case is to support cooperative multiple inheritance in adynamic execution environment. This use case is unique to Python and isnot found in statically compiled languages or languages that only supportsingle inheritance. This makes it possible to implement “diamond diagrams”where multiple base classes implement the same method. Good design dictatesthat this method have the same calling signature in every case (because theorder of calls is determined at runtime, because that order adaptsto changes in the class hierarchy, and because that order can includesibling classes that are unknown prior to runtime).
For both use cases, a typical superclass call looks like this:
classC(B):defmethod(self,arg):super(C,self).method(arg)
Note that
super()
is implemented as part of the binding process forexplicit dotted attribute lookups such assuper().__getitem__(name)
.It does so by implementing its own__getattribute__()
method for searchingclasses in a predictable order that supports cooperative multiple inheritance.Accordingly,super()
is undefined for implicit lookups using statements oroperators such assuper()[name]
.Also note that
super()
is not limited to use inside methods. The twoargument form specifies the arguments exactly and makes the appropriatereferences.For practical suggestions on how to design cooperative classes using
super()
, seeguide to using super().New in version 2.2.
tuple
([iterable])¶Return a tuple whose items are the same and in the same order asiterable’sitems.iterable may be a sequence, a container that supports iteration, or aniterator object. Ifiterable is already a tuple, it is returned unchanged.For instance,
tuple('abc')
returns('a','b','c')
andtuple([1,2,3])
returns(1,2,3)
. If no argument is given, returns a new emptytuple,()
.tuple
is an immutable sequence type, as documented inSequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built indict
,list
, andset
classes, and thecollections
module.
- class
type
(object)¶ - class
type
(name,bases,dict) With one argument, return the type of anobject. The return value is atype object. The
isinstance()
built-in function is recommended fortesting the type of an object.With three arguments, return a new type object. This is essentially adynamic form of the
class
statement. Thename string is theclass name and becomes the__name__
attribute; thebases tupleitemizes the base classes and becomes the__bases__
attribute;and thedict dictionary is the namespace containing definitions for classbody and becomes the__dict__
attribute. For example, thefollowing two statements create identicaltype
objects:>>>classX(object):...a=1...>>>X=type('X',(object,),dict(a=1))
New in version 2.2.
unichr
(i)¶Return the Unicode string of one character whose Unicode code is the integeri. For example,
unichr(97)
returns the stringu'a'
. This is theinverse oford()
for Unicode strings. The valid range for the argumentdepends how Python was configured – it may be either UCS2 [0..0xFFFF] or UCS4[0..0x10FFFF].ValueError
is raised otherwise. For ASCII and 8-bitstrings seechr()
.New in version 2.0.
unicode
(object='')¶unicode
(object[,encoding[,errors]])Return the Unicode string version ofobject using one of the following modes:
Ifencoding and/orerrors are given,
unicode()
will decode the objectwhich can either be an 8-bit string or a character buffer using the codec forencoding. Theencoding parameter is a string giving the name of an encoding;if the encoding is not known,LookupError
is raised. Error handling isdone according toerrors; this specifies the treatment of characters which areinvalid in the input encoding. Iferrors is'strict'
(the default), aValueError
is raised on errors, while a value of'ignore'
causeserrors to be silently ignored, and a value of'replace'
causes the officialUnicode replacement character,U+FFFD
, to be used to replace inputcharacters which cannot be decoded. See also thecodecs
module.If no optional parameters are given,
unicode()
will mimic the behaviour ofstr()
except that it returns Unicode strings instead of 8-bit strings. Moreprecisely, ifobject is a Unicode string or subclass it will return thatUnicode string without any additional decoding applied.For objects which provide a
__unicode__()
method, it will call this methodwithout arguments to create a Unicode string. For all other objects, the 8-bitstring version or representation is requested and then converted to a Unicodestring using the codec for the default encoding in'strict'
mode.For more information on Unicode strings seeSequence Types — str, unicode, list, tuple, bytearray, buffer, xrange which describessequence functionality (Unicode strings are sequences), and also thestring-specific methods described in theString Methods section. Tooutput formatted strings use template strings or the
%
operator describedin theString Formatting Operations section. In addition see theString Services section. See alsostr()
.New in version 2.0.
Changed in version 2.2:Support for
__unicode__()
added.
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, new-style classes use adictproxy to prevent direct dictionary updates).Without an argument,
vars()
acts likelocals()
. Note, thelocals dictionary is only useful for reads since updates to the localsdictionary are ignored.
xrange
(stop)¶xrange
(start,stop[,step])This function is very similar to
range()
, but returns anxrangeobjectinstead of a list. This is an opaque sequence type which yields the same valuesas the corresponding list, without actually storing them all simultaneously.The advantage ofxrange()
overrange()
is minimal (sincexrange()
still has to create the values when asked for them) except when avery large range is used on a memory-starved machine or when all of the range’selements are never used (such as when the loop is usually terminated withbreak
). For more information on xrange objects, seeXRange Type andSequence Types — str, unicode, list, tuple, bytearray, buffer, xrange.CPython implementation detail:
xrange()
is intended to be simple and fast. Implementations mayimpose restrictions to achieve this. The C implementation of Pythonrestricts all arguments to native C longs (“short” Python integers), andalso requires that the number of elements fit in a native C long. If alarger range is needed, an alternate version can be crafted using theitertools
module:islice(count(start,step),(stop-start+step-1+2*(step<0))//step)
.
zip
([iterable,...])¶This function returns a list of tuples, where thei-th tuple contains thei-th element from each of the argument sequences or iterables. The returnedlist is truncated in length to the length of the shortest argument sequence.When there are multiple arguments which are all of the same length,
zip()
is similar tomap()
with an initial argument ofNone
. With a singlesequence argument, it returns a list of 1-tuples. With no arguments, it returnsan empty list.The left-to-right evaluation order of the iterables is guaranteed. Thismakes possible an idiom for clustering a data series into n-length groupsusing
zip(*[iter(s)]*n)
.zip()
in conjunction with the*
operator can be used to unzip alist:>>>x=[1,2,3]>>>y=[4,5,6]>>>zipped=zip(x,y)>>>zipped[(1, 4), (2, 5), (3, 6)]>>>x2,y2=zip(*zipped)>>>x==list(x2)andy==list(y2)True
New in version 2.0.
__import__
(name[,globals[,locals[,fromlist[,level]]]])¶Note
This is an advanced function that is not needed in everyday Pythonprogramming, unlike
importlib.import_module()
.This function is invoked by the
import
statement. It can bereplaced (by importing the__builtin__
module and assigning to__builtin__.__import__
) in order to change semantics of theimport
statement, but nowadays it is usually simpler to use importhooks (seePEP 302). Direct use of__import__()
is rare, except incases where you want to import a module whose name is only known at runtime.The function imports the modulename, potentially using the givenglobalsandlocals to determine how to interpret the name in a package context.Thefromlist gives the names of objects or submodules that should beimported from the module given byname. The standard implementation doesnot use itslocals argument at all, and uses itsglobals only todetermine the package context of the
import
statement.level specifies whether to use absolute or relative imports. The defaultis
-1
which indicates both absolute and relative imports will beattempted.0
means only perform absolute imports. Positive values forlevel indicate the number of parent directories to search relative to thedirectory of the module calling__import__()
.When thename variable is of the form
package.module
, normally, thetop-level package (the name up till the first dot) is returned,not themodule named byname. However, when a non-emptyfromlist argument isgiven, the module named byname is returned.For example, the statement
importspam
results in bytecode resembling thefollowing code:spam=__import__('spam',globals(),locals(),[],-1)
The statement
importspam.ham
results in this call:spam=__import__('spam.ham',globals(),locals(),[],-1)
Note how
__import__()
returns the toplevel module here because this isthe object that is bound to a name by theimport
statement.On the other hand, the statement
fromspam.hamimporteggs,sausageassaus
results in_temp=__import__('spam.ham',globals(),locals(),['eggs','sausage'],-1)eggs=_temp.eggssaus=_temp.sausage
Here, the
spam.ham
module is returned from__import__()
. From thisobject, the names to import are retrieved and assigned to their respectivenames.If you simply want to import a module (potentially within a package) by name,use
importlib.import_module()
.Changed in version 2.5:The level parameter was added.
Changed in version 2.5:Keyword support for parameters was added.
3.Non-essential Built-in Functions¶
There are several built-in functions that are no longer essential to learn, knowor use in modern Python programming. They have been kept here to maintainbackwards compatibility with programs written for older versions of Python.
Python programmers, trainers, students and book writers should feel free tobypass these functions without concerns about missing something important.
apply
(function,args[,keywords])¶Thefunction argument must be a callable object (a user-defined or built-infunction or method, or a class object) and theargs argument must be asequence. Thefunction is called withargs as the argument list; the numberof arguments is the length of the tuple. If the optionalkeywords argument ispresent, it must be a dictionary whose keys are strings. It specifies keywordarguments to be added to the end of the argument list. Calling
apply()
isdifferent from just callingfunction(args)
, since in that case there isalways exactly one argument. The use ofapply()
is equivalent tofunction(*args,**keywords)
.Deprecated since version 2.3:Use
function(*args,**keywords)
instead ofapply(function,args,keywords)
(seeUnpacking Argument Lists).
buffer
(object[,offset[,size]])¶Theobject argument must be an object that supports the buffer call interface(such as strings, arrays, and buffers). A new buffer object will be createdwhich references theobject argument. The buffer object will be a slice fromthe beginning ofobject (or from the specifiedoffset). The slice willextend to the end ofobject (or will have a length given by thesizeargument).
coerce
(x,y)¶Return a tuple consisting of the two numeric arguments converted to a commontype, using the same rules as used by arithmetic operations. If coercion is notpossible, raise
TypeError
.
intern
(string)¶Enterstring in the table of “interned” strings and return the interned string– which isstring itself or a copy. Interning strings is useful to gain alittle performance on dictionary lookup – if the keys in a dictionary areinterned, and the lookup key is interned, the key comparisons (after hashing)can be done by a pointer compare instead of a string compare. Normally, thenames used in Python programs are automatically interned, and the dictionariesused to hold module, class or instance attributes have interned keys.
Changed in version 2.3:Interned strings are not immortal (like they used to be in Python 2.2 andbefore); you must keep a reference to the return value of
intern()
aroundto benefit from it.
Footnotes
- 1
It is used relatively rarely so does not warrant being made into a statement.
- 2
Specifying a buffer size currently has no effect on systems that don’t have
setvbuf()
. The interface to specify the buffer size is not done using amethod that callssetvbuf()
, because that may dump core when called afterany I/O has been performed, and there’s no reliable way to determine whetherthis is the case.- 3
In the current implementation, local variable bindings cannot normally beaffected this way, but variables retrieved from other scopes (such as modules)can be. This may change.