Built-In Functions - Python 2.7
Built-In Functions - Python 2.7
2.BuiltinFunctionsPython2.7.9documentation
2. Builtin Functions
ThePythoninterpreterhasanumberoffunctionsbuiltintoitthatarealwaysavailable.They
arelistedhereinalphabeticalorder.
Builtin
Functions
abs()
divmod()
input()
open()
staticmethod()
all()
enumerate()
int()
ord()
str()
any()
eval()
isinstance()
pow()
sum()
basestring()
execfile()
issubclass()
print()
super()
bin()
file()
iter()
property()
tuple()
bool()
filter()
len()
range()
type()
bytearray()
float()
list()
raw_input()
unichr()
callable()
format()
locals()
reduce()
unicode()
chr()
frozenset()
long()
reload()
vars()
classmethod()
getattr()
map()
repr()
xrange()
cmp()
globals()
max()
reversed()
zip()
compile()
hasattr()
memoryview()
round()
__import__()
complex()
hash()
min()
set()
apply()
delattr()
help()
next()
setattr()
buffer()
dict()
hex()
object()
slice()
coerce()
dir()
id()
oct()
sorted()
intern()
abs (x)
Returntheabsolutevalueofanumber.Theargumentmaybeaplainorlongintegeror
afloatingpointnumber.Iftheargumentisacomplexnumber,itsmagnitudeisreturned.
all (iterable)
Return True ifallelementsoftheiterablearetrue(oriftheiterableisempty).Equivalent
to:
defall(iterable):
forelementiniterable:
ifnotelement:
returnFalse
returnTrue
Newinversion2.5.
any (iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False .
Equivalentto:
defany(iterable):
forelementiniterable:
ifelement:
https://docs.python.org/2/library/functions.html#builtinfuncs
1/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
returnTrue
returnFalse
Newinversion2.5.
basestring ()
This abstract type is the superclass for str and unicode . It cannot be called or
instantiated,butitcanbeusedtotestwhetheranobjectisaninstanceof str or unicode .
isinstance(obj,basestring) isequivalentto isinstance(obj,(str,unicode)) .
Newinversion2.3.
bin (x)
Convertanintegernumbertoabinarystring.TheresultisavalidPythonexpression.If
x is not a Python int object, it has to define an __index__() method that returns an
integer.
Newinversion2.6.
class bool ([x])
ReturnaBooleanvalue,i.e.oneof True or False .xisconvertedusingthestandardtruth
testing procedure. If x is false or omitted, this returns False otherwise it returns True .
bool isalsoaclass,whichisasubclassof int .Class bool cannotbesubclassedfurther.
Itsonlyinstancesare False and True .
Newinversion2.2.1.
Changedinversion2.3:Ifnoargumentisgiven,thisfunctionreturns False .
class bytearray ([source[,encoding[,errors]]])
Returnanewarrayofbytes.The bytearray classisamutablesequenceofintegersin
the range 0 <= x < 256. It has most of the usual methods of mutable sequences,
describedinMutableSequenceTypes,aswellasmostmethodsthatthe str typehas,
seeStringMethods.
The optional source parameter can be used to initialize the array in a few different
ways:
If it is unicode, you must also give the encoding (and optionally, errors)
parameters bytearray() thenconvertstheunicodetobytesusing unicode.encode() .
Ifitisaninteger,thearraywillhavethatsizeandwillbeinitializedwithnullbytes.
Ifitisanobjectconformingtothebufferinterface,areadonlybufferoftheobject
willbeusedtoinitializethebytesarray.
Ifitisaniterable,itmustbeaniterableofintegersintherange 0<=x<256 ,which
areusedastheinitialcontentsofthearray.
Withoutanargument,anarrayofsize0iscreated.
https://docs.python.org/2/library/functions.html#builtinfuncs
2/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
Newinversion2.6.
callable (object)
Return True iftheobjectargumentappearscallable, False ifnot.Ifthisreturnstrue,itis
stillpossiblethatacallfails,butifitisfalse,callingobjectwillneversucceed.Notethat
classes are callable (calling a class returns a new instance) class instances are
callableiftheyhavea __call__() method.
chr (i)
ReturnastringofonecharacterwhoseASCIIcodeistheintegeri.Forexample, chr(97)
returnsthestring 'a' .Thisistheinverseof ord() .Theargumentmustbeintherange
[0..255],inclusive ValueError willberaisedifiisoutsidethatrange.Seealso unichr() .
classmethod (function)
Returnaclassmethodforfunction.
A class method receives the class as implicit first argument, just like an instance
methodreceivestheinstance.Todeclareaclassmethod,usethisidiom:
classC(object):
@classmethod
deff(cls,arg1,arg2,...):
...
3/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
Latin1 encoded string or an AST object. Refer to the ast module documentation for
informationonhowtoworkwithASTobjects.
Thefilenameargumentshouldgivethefilefromwhichthecodewasreadpasssome
recognizablevalueifitwasntreadfromafile( '<string>' iscommonlyused).
Themode argument specifies what kind of code must be compiled it can be 'exec' if
sourceconsistsofasequenceofstatements, 'eval' ifitconsistsofasingleexpression,
or 'single' ifitconsistsofasingleinteractivestatement(inthelattercase,expression
statementsthatevaluatetosomethingotherthan None willbeprinted).
The optional arguments flags and dont_inherit control which future statements (see
PEP236) affect the compilation of source. If neither is present (or both are zero) the
codeiscompiledwiththosefuturestatementsthatareineffectinthecodethatiscalling
compile() . If the flags argument is given and dont_inherit is not (or is zero) then the
future statements specified by the flags argument are used in addition to those that
wouldbeusedanyway.Ifdont_inheritisanonzerointegerthentheflagsargumentisit
thefuturestatementsineffectaroundthecalltocompileareignored.
FuturestatementsarespecifiedbybitswhichcanbebitwiseORedtogethertospecify
multiplestatements.Thebitfieldrequiredtospecifyagivenfeaturecanbefoundasthe
compiler_flag attributeonthe _Feature instanceinthe __future__ module.
This function raises SyntaxError if the compiled source is invalid, and TypeError if the
sourcecontainsnullbytes.
IfyouwanttoparsePythoncodeintoitsASTrepresentation,see ast.parse() .
Note: Whencompilingastringwithmultilinecodein 'single' or 'eval' mode,input
mustbeterminatedbyatleastonenewlinecharacter.Thisistofacilitatedetectionof
incompleteandcompletestatementsinthe code module.
Changedinversion2.3:Theflagsanddont_inheritargumentswereadded.
Changedinversion2.6:SupportforcompilingASTobjects.
Changedinversion2.7:AlloweduseofWindowsandMacnewlines.Alsoinputin 'exec'
modedoesnothavetoendinanewlineanymore.
class complex ([real[,imag]])
Returnacomplexnumberwiththevaluereal+imag*jorconvertastringornumbertoa
complex number. If the first parameter is a string, it will be interpreted as a complex
number and the function must be called without a second parameter. The second
parameter can never be a string. Each argument may be any numeric type (including
complex). If imag is omitted, it defaults to zero and the function serves as a numeric
https://docs.python.org/2/library/functions.html#builtinfuncs
4/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
list , set ,
and
tuple
dir ([object])
Without arguments, return the list of names in the current local scope. With an
argument,attempttoreturnalistofvalidattributesforthatobject.
5/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
attributes,andrecursivelyoftheattributesofitsclasssbaseclasses.
Theresultinglistissortedalphabetically.Forexample:
>>>importstruct
>>>dir()#showthenamesinthemodulenamespace
['__builtins__','__doc__','__name__','struct']
>>>dir(struct)#showthenamesinthestructmodule
['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']
>>>
>>>
Equivalentto:
defenumerate(sequence,start=0):
n=start
https://docs.python.org/2/library/functions.html#builtinfuncs
6/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
foreleminsequence:
yieldn,elem
n+=1
Newinversion2.3.
Changedinversion2.6:Thestartparameterwasadded.
eval (expression[,globals[,locals]])
TheargumentsareaUnicodeorLatin1encodedstringandoptionalglobalsandlocals.
Ifprovided,globalsmustbeadictionary.Ifprovided,localscanbeanymappingobject.
Changedinversion2.4:formerlylocalswasrequiredtobeadictionary.
TheexpressionargumentisparsedandevaluatedasaPythonexpression(technically
speaking,aconditionlist)usingtheglobalsandlocalsdictionariesasglobalandlocal
namespace. If the globals dictionary is present and lacks __builtins__, the current
globalsarecopiedintoglobalsbeforeexpressionisparsed.Thismeansthatexpression
normallyhasfullaccesstothestandard __builtin__ moduleandrestrictedenvironments
arepropagated.Ifthelocalsdictionaryisomitteditdefaultstotheglobalsdictionary.If
both dictionaries are omitted, the expression is executed in the environment where
eval() iscalled.Thereturnvalueistheresultoftheevaluatedexpression.Syntaxerrors
arereportedasexceptions.Example:
>>>x=1
>>>printeval('x+1')
2
>>>
Thisfunctioncanalsobeusedtoexecutearbitrarycodeobjects(suchasthosecreated
by compile() ).Inthiscasepassacodeobjectinsteadofastring.Ifthecodeobjecthas
beencompiledwith 'exec' asthemodeargument, eval() sreturnvaluewillbe None .
Hints:dynamicexecutionofstatementsissupportedbythe exec statement.Execution
of statements from a file is supported by the execfile() function. The globals() and
locals() functions returns the current global and local dictionary, respectively, which
maybeusefultopassaroundforuseby eval() or execfile() .
See ast.literal_eval() for a function that can safely evaluate strings with expressions
containingonlyliterals.
execfile (filename[,globals[,locals]])
Thisfunctionissimilartothe exec statement,butparsesafileinsteadofastring.It is
differentfromthe import statementinthatitdoesnotusethemoduleadministrationit
readsthefileunconditionallyanddoesnotcreateanewmodule.[1]
The arguments are a file name and two optional dictionaries. The file is parsed and
evaluatedasasequenceofPythonstatements(similarlytoamodule)usingtheglobals
https://docs.python.org/2/library/functions.html#builtinfuncs
7/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
andlocals dictionaries as global and local namespace. If provided, locals can be any
mapping object. Remember that at module level, globals and locals are the same
dictionary. If two separate objects are passed as globals and locals, the code will be
executedasifitwereembeddedinaclassdefinition.
Changedinversion2.4:formerlylocalswasrequiredtobeadictionary.
Ifthelocalsdictionaryisomitteditdefaultstotheglobalsdictionary.Ifbothdictionaries
areomitted,theexpressionisexecutedintheenvironmentwhere execfile() iscalled.
Thereturnvalueis None .
Note: Thedefaultlocalsactasdescribedforfunction locals() below:modifications
to the default locals dictionary should not be attempted. Pass an explicit locals
dictionary if you need to see effects of the code on locals after function execfile()
returns. execfile() cannotbeusedreliablytomodifyafunctionslocals.
file (name[,mode[,buffering]])
Constructor function for the file type, described further in section File Objects. The
constructorsargumentsarethesameasthoseofthe open() builtinfunctiondescribed
below.
When opening a file, its preferable to use open() instead of invoking this constructor
directly. file ismoresuitedtotypetesting(forexample,writing isinstance(f,file) ).
Newinversion2.2.
filter (function,iterable)
Constructalistfromthoseelementsofiterableforwhichfunctionreturnstrue.iterable
maybeeitherasequence,acontainerwhichsupportsiteration,oraniterator.Ifiterable
isastringoratuple,theresultalsohasthattypeotherwiseitisalwaysalist.Iffunction
is None ,theidentityfunctionisassumed,thatis,allelementsofiterablethatarefalseare
removed.
Note that
filter(function, iterable)
8/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
]inf.Otherwise,theargumentmaybeaplainorlongintegerorafloatingpointnumber,
and a floating point number with the same value (within Pythons floating point
precision)isreturned.Ifnoargumentisgiven,returns 0.0 .
Note: When passing in a string, values for NaN and Infinity may be returned,
dependingontheunderlyingClibrary.Floatacceptsthestringsnan,infandinffor
NaNandpositiveornegativeinfinity.Thecaseandaleading+areignoredaswellas
aleadingisignoredforNaN.FloatalwaysrepresentsNaNandinfinityasnan,infor
inf.
ThefloattypeisdescribedinNumericTypesint,float,long,complex.
format (value[,format_spec])
Convert a value to a formatted representation, as controlled by format_spec. The
interpretationofformat_spec will depend on the type of the value argument, however
there is a standard formatting syntax that is used by most builtin types: Format
SpecificationMiniLanguage.
9/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
>>>
If x is not a Python int or long object, it has to define an __index__() method that
returnsaninteger.
Seealso int() forconvertingahexadecimalstringtoanintegerusingabaseof16.
Note: Toobtainahexadecimalstringrepresentationforafloat,usethe float.hex()
method.
Changedinversion2.4:Formerlyonlyreturnedanunsignedliteral.
id (object)
Returntheidentityofanobject.Thisisaninteger(orlonginteger)whichisguaranteed
to be unique and constant for this object during its lifetime. Two objects with non
overlappinglifetimesmayhavethesame id() value.
https://docs.python.org/2/library/functions.html#builtinfuncs
10/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
CPythonimplementationdetail:Thisistheaddressoftheobjectinmemory.
input ([prompt])
Equivalentto eval(raw_input(prompt)) .
This function does not catch user errors. If the input is not syntactically valid, a
SyntaxError will be raised. Other exceptions may be raised if there is an error during
evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line
editingandhistoryfeatures.
Considerusingthe raw_input() functionforgeneralinputfromusers.
class int (x=0)
class int (x,base=10)
Return an integer object constructed from a number or string x, or return 0 if no
arguments are given. If x is a number, it can be a plain integer, a long integer, or a
floatingpointnumber.Ifxisfloatingpoint,theconversiontruncatestowardszero.Ifthe
argumentisoutsidetheintegerrange,thefunctionreturnsalongobjectinstead.
If x is not a number or if base is given, then x must be a string or Unicode object
representinganintegerliteralinradixbase.Optionally,theliteralcanbeprecededby +
or (withnospaceinbetween)andsurroundedbywhitespace.Abasenliteralconsists
ofthedigits0ton1,with a to z (or A to Z )havingvalues10to35.Thedefaultbaseis
10. The allowed values are 0 and 236. Base2, 8, and 16 literals can be optionally
prefixedwith 0b / 0B , 0o / 0O / 0 ,or 0x / 0X , as with integer literals in code. Base 0 means to
interpretthestringexactlyasanintegerliteral,sothattheactualbaseis2,8,10,or16.
TheintegertypeisdescribedinNumericTypesint,float,long,complex.
isinstance (object,classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a
(direct,indirectorvirtual)subclassthereof.Alsoreturntrueifclassinfoisatypeobject
(newstyleclass)andobject is an object of that type or of a (direct, indirect or virtual)
subclass thereof. If object is not a class instance or an object of the given type, the
function always returns false. Ifclassinfo is neither a class object nor a type object, it
may be a tuple of class or type objects, or may recursively contain other such tuples
(other sequence types are not accepted). If classinfo is not a class, type, or tuple of
classes,types,andsuchtuples,a TypeError exceptionisraised.
Changedinversion2.2:Supportforatupleoftypeinformationwasadded.
issubclass (class,classinfo)
https://docs.python.org/2/library/functions.html#builtinfuncs
11/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
One useful application of the second form of iter() is to read lines of a file until a
certain line is reached. The following example reads a file until the readline() method
returnsanemptystring:
withopen('mydata.txt')asfp:
forlineiniter(fp.readline,''):
process_line(line)
Newinversion2.2.
len (s)
Returnthelength(thenumberofitems)ofanobject.Theargumentmaybeasequence
(suchasastring,bytes,tuple,list,orrange)oracollection(suchasadictionary,set,or
frozenset).
12/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
Ifonepositionalargumentisprovided,iterablemustbeanonemptyiterable(suchasa
nonemptystring,tupleorlist).Thelargestitemintheiterableisreturned.Iftwoormore
positionalargumentsareprovided,thelargestofthepositionalargumentsisreturned.
Theoptionalkeyargumentspecifiesaoneargumentorderingfunctionlikethatusedfor
list.sort() . The key argument, if supplied, must be in keyword form (for example,
max(a,b,c,key=func) ).
Changedinversion2.5:Addedsupportfortheoptionalkeyargument.
memoryview (obj)
Returnamemoryviewobjectcreatedfromthegivenargument.Seememoryviewtype
formoreinformation.
https://docs.python.org/2/library/functions.html#builtinfuncs
13/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
min (iterable[,key])
min (arg1,arg2,*args[,key])
Returnthesmallestiteminaniterableorthesmallestoftwoormorearguments.
Ifonepositionalargumentisprovided,iterablemustbeanonemptyiterable(suchasa
nonempty string, tuple or list). The smallest item in the iterable is returned. If two or
more positional arguments are provided, the smallest of the positional arguments is
returned.
Theoptionalkeyargumentspecifiesaoneargumentorderingfunctionlikethatusedfor
list.sort() . The key argument, if supplied, must be in keyword form (for example,
min(a,b,c,key=func) ).
Changedinversion2.5:Addedsupportfortheoptionalkeyargument.
next (iterator[,default])
Retrievethenextitemfromtheiteratorbycallingits next() method.Ifdefaultisgiven,it
isreturnediftheiteratorisexhausted,otherwise StopIteration israised.
Newinversion2.6.
class object
Return a new featureless object. object is a base for all new style classes. It has the
methodsthatarecommontoallinstancesofnewstyleclasses.
Newinversion2.2.
Changed in version 2.3: This function does not accept any arguments. Formerly, it
acceptedargumentsbutignoredthem.
oct (x)
Convertanintegernumber(ofanysize)toanoctalstring.TheresultisavalidPython
expression.
Changedinversion2.4:Formerlyonlyreturnedanunsignedliteral.
open (name[,mode[,buffering]])
Openafile,returninganobjectofthe file typedescribedinsectionFileObjects.Ifthe
file cannot be opened, IOError is raised. When opening a file, its preferable to use
open() insteadofinvokingthe file constructordirectly.
14/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
thatall writes append to the end of the file regardless of the current seek position). If
modeisomitted,itdefaultsto 'r' .Thedefaultistousetextmode,whichmayconvert
'\n' characters to a platformspecific representation on writing and back on reading.
Thus,whenopeningabinaryfile,youshouldappend 'b' tothemodevaluetoopenthe
file in binary mode, which will improve portability. (Appending 'b' is useful even on
systems that dont treat binary and text files differently, where it serves as
documentation.)Seebelowformorepossiblevaluesofmode.
The optional buffering argument specifies the files desired buffer size: 0 means
unbuffered, 1 means line buffered, any other positive value means use a buffer of
(approximately) that size (in bytes). A negative buffering means to use the system
default,whichisusuallylinebufferedforttydevicesandfullybufferedforotherfiles.If
omitted,thesystemdefaultisused.[2]
Modes 'r+' , 'w+' and 'a+' openthefileforupdating(readingandwriting)notethat 'w+'
truncatesthefile.Append 'b' tothemodetoopenthefileinbinarymode,onsystems
that differentiate between binary and text files on systems that dont have this
distinction,addingthe 'b' hasnoeffect.
Inadditiontothestandard fopen() valuesmode may be 'U' or 'rU' .Python is usually
builtwithuniversalnewlinessupportsupplying 'U' opensthefileasatextfile,butlines
may be terminated by any of the following: the Unix endofline convention '\n' , the
Macintosh convention '\r' , or the Windows convention '\r\n' . All of these external
representations are seen as '\n' by the Python program. If Python is built without
universalnewlinessupportamodewith 'U' isthesameasnormaltextmode.Notethat
fileobjectssoopenedalsohaveanattributecalled newlines whichhasavalueof None (if
nonewlineshaveyetbeenseen), '\n' , '\r' , '\r\n' ,oratuplecontainingallthenewline
typesseen.
Pythonenforcesthatthemode,afterstripping 'U' ,beginswith 'r' , 'w' or 'a' .
Python provides many file handling modules including fileinput , os , os.path , tempfile ,
and shutil .
Changedinversion2.5:Restrictiononfirstletterofmodestringintroduced.
ord (c)
Givenastringoflengthone,returnanintegerrepresentingtheUnicodecodepointof
thecharacterwhentheargumentisaunicodeobject,orthevalueofthebytewhenthe
argumentisan8bitstring.Forexample, ord('a') returnstheinteger 97 , ord(u'\u2020')
returns 8224 . This is the inverse of chr() for 8bit strings and of unichr() for unicode
objects.IfaunicodeargumentisgivenandPythonwasbuiltwithUCS2Unicode,then
thecharacterscodepointmustbeintherange[0..65535]inclusiveotherwisethestring
lengthistwo,anda TypeError willberaised.
https://docs.python.org/2/library/functions.html#builtinfuncs
15/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
pow (x,y[,z])
Returnx to the power yifz is present, return x to the power y, modulo z (computed
more efficiently than pow(x,y)% z ). The twoargument form pow(x, y) is equivalent to
usingthepoweroperator: x**y .
Theargumentsmusthavenumerictypes.Withmixedoperandtypes,thecoercionrules
forbinaryarithmeticoperators apply.For int and long int operands, the result has the
sametypeastheoperands(aftercoercion)unlessthesecondargumentisnegativein
that case, all arguments are converted to float and a float result is delivered. For
example, 10**2 returns 100 , but 10**2 returns 0.01 . (This last feature was added in
Python2.2.InPython2.1andbefore,ifbothargumentswereofintegertypesandthe
second argument was negative, an exception was raised.) If the second argument is
negative,thethirdargumentmustbeomitted.Ifzispresent,xandymustbeofinteger
types,andymustbenonnegative.(ThisrestrictionwasaddedinPython2.2.InPython
2.1 and before, floating 3argument pow() returned platformdependent results
dependingonfloatingpointroundingaccidents.)
print (*objects,sep='',end='\n',file=sys.stdout)
Printobjectstothestreamfile,separatedbysepandfollowedbyend.sep,endandfile,
ifpresent,mustbegivenaskeywordarguments.
All nonkeyword arguments are converted to strings like str() does and written to the
stream,separatedbysepandfollowedbyend.Bothsepandendmustbestringsthey
canalsobe None ,whichmeanstousethedefaultvalues.Ifnoobjectsaregiven, print()
willjustwriteend.
Thefileargumentmustbeanobjectwitha write(string) methodifitisnotpresentor
None , sys.stdout willbeused.Outputbufferingisdeterminedbyfile.Use file.flush() to
ensure,forinstance,immediateappearanceonascreen.
Note: This function is not normally available as a builtin since the name print is
recognized as the print statement. To disable the statement and use the print()
function,usethisfuturestatementatthetopofyourmodule:
from__future__importprint_function
Newinversion2.6.
class property ([fget[,fset[,fdel[,doc]]]])
Returnapropertyattributefornewstyleclasses(classesthatderivefrom object ).
fgetisafunctionforgettinganattributevalue.fsetisafunctionforsettinganattribute
value.fdelisafunctionfordeletinganattributevalue.Anddoccreatesadocstringfor
theattribute.
https://docs.python.org/2/library/functions.html#builtinfuncs
16/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
Atypicaluseistodefineamanagedattribute x :
classC(object):
def__init__(self):
self._x=None
defgetx(self):
returnself._x
defsetx(self,value):
self._x=value
defdelx(self):
delself._x
x=property(getx,setx,delx,"I'mthe'x'property.")
The @property decorator turns the voltage() method into a getter for a readonly
attribute with the same name, and it sets the docstring for voltage to Get the current
voltage.
A property object has getter , setter , and deleter methods usable as decorators that
create a copy of the property with the corresponding accessor function set to the
decoratedfunction.Thisisbestexplainedwithanexample:
classC(object):
def__init__(self):
self._x=None
@property
defx(self):
"""I'mthe'x'property."""
returnself._x
@x.setter
defx(self,value):
self._x=value
https://docs.python.org/2/library/functions.html#builtinfuncs
17/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
@x.deleter
defx(self):
delself._x
This code is exactly equivalent to the first example. Be sure to give the additional
functionsthesamenameastheoriginalproperty( x inthiscase.)
Thereturnedpropertyobjectalsohastheattributes fget , fset ,and fdel corresponding
totheconstructorarguments.
Newinversion2.2.
Changedinversion2.5:Usefgetsdocstringifnodocgiven.
Changedinversion2.6:The getter , setter ,and deleter attributeswereadded.
range (stop)
range (start,stop[,step])
Thisisaversatilefunctiontocreatelistscontainingarithmeticprogressions.Itismost
oftenusedin for loops.Theargumentsmustbeplainintegers.Ifthestepargumentis
omitted, it defaults to 1 .Ifthestart argument is omitted, it defaults to 0 . The full form
returns a list of plain integers [start, start + step, start + 2 * step, ...] . If step is
positive, the last element is the largest start + i * step less than stop if step is
negative,thelastelementisthesmallest start+i*step greaterthanstop.stepmust
notbezero(orelse ValueError israised).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 the prompt argument is present, it is written to standard output without a trailing
newline. The function then reads a line from input, converts it to a string (stripping a
trailingnewline),andreturnsthat.WhenEOFisread, EOFError israised.Example:
>>>s=raw_input('>')
>MontyPython'sFlyingCircus
>>>s
"MontyPython'sFlyingCircus"
https://docs.python.org/2/library/functions.html#builtinfuncs
>>>
18/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
reload (module)
Reload a previously imported module. The argument must be a module object, so it
must have been successfully imported before. This is useful if you have edited the
modulesourcefileusinganexternaleditorandwanttotryoutthenewversionwithout
leavingthePythoninterpreter.Thereturnvalueisthemoduleobject(thesameasthe
moduleargument).
19/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
It is legal though generally not very useful to reload builtin or dynamically loaded
modules, except for sys , __main__ and __builtin__ . In many cases, however, extension
modules are not designed to be initialized more than once, and may fail in arbitrary
wayswhenreloaded.
Ifamoduleimportsobjectsfromanothermoduleusing from ... import ...,calling reload()
fortheothermoduledoesnotredefinetheobjectsimportedfromitonewayaround
this is to reexecute the from statement, another is to use import and qualified names
(module.*name*)instead.
Ifamoduleinstantiatesinstancesofaclass,reloadingthemodulethatdefinestheclass
doesnotaffectthemethoddefinitionsoftheinstancestheycontinuetousetheold
classdefinition.Thesameistrueforderivedclasses.
repr (object)
Return a string containing a printable representation of an object. This is the same
value yielded by conversions (reverse quotes). It is sometimes useful to be able to
accessthisoperationasanordinaryfunction.Formanytypes,thisfunctionmakesan
attempttoreturnastringthatwouldyieldanobjectwiththesamevaluewhenpassedto
eval() ,otherwisetherepresentationisastringenclosedinanglebracketsthatcontains
the name of the type of the object together with additional information often including
thenameandaddressoftheobject.Aclasscancontrolwhatthisfunctionreturnsforits
instancesbydefininga __repr__() method.
reversed (seq)
Returnareverseiterator.seqmustbeanobjectwhichhasa __reversed__() methodor
supports the sequence protocol (the __len__() method and the __getitem__() method
withintegerargumentsstartingat 0 ).
Newinversion2.4.
Changedinversion2.6:Addedthepossibilitytowriteacustom __reversed__() method.
https://docs.python.org/2/library/functions.html#builtinfuncs
20/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
round (number[,ndigits])
Returnthefloatingpointvaluenumberroundedtondigitsdigitsafterthedecimalpoint.
Ifndigitsisomitted,itdefaultstozero.Theresultisafloatingpointnumber.Valuesare
rounded to the closest multiple of 10 to the power minus ndigits if two multiples are
equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and
round(0.5) is 1.0 ).
Theoptionalargumentscmp,key,andreversehavethesamemeaningasthoseforthe
list.sort() method(describedinsectionMutableSequenceTypes).
cmp specifies a custom comparison function of two arguments (iterable elements)
https://docs.python.org/2/library/functions.html#builtinfuncs
21/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
whichshouldreturnanegative,zeroorpositivenumberdependingonwhetherthefirst
argument is considered smaller than, equal to, or larger than the second argument:
cmp=lambdax,y:cmp(x.lower(),y.lower()) .Thedefaultvalueis None .
keyspecifiesafunctionofoneargumentthatisusedtoextractacomparisonkeyfrom
each list element: key=str.lower . The default value is None (compare the elements
directly).
reverse is a boolean value. If set to True , then the list elements are sorted as if each
comparisonwerereversed.
Ingeneral,thekeyandreverseconversionprocessesaremuchfasterthanspecifying
anequivalentcmp function. This is because cmp is called multiple times for each list
element while key and reverse touch each element only once. Use
functools.cmp_to_key() toconvertanoldstylecmpfunctiontoakeyfunction.
Thebuiltin sorted() functionisguaranteedtobestable.Asortisstableifitguarantees
not to change the relative order of elements that compare equal this is helpful for
sortinginmultiplepasses(forexample,sortbydepartment,thenbysalarygrade).
Forsortingexamplesandabriefsortingtutorial,seeSortingHOWTO.
Newinversion2.4.
staticmethod (function)
Returnastaticmethodforfunction.
Astaticmethoddoesnotreceiveanimplicitfirstargument.Todeclareastaticmethod,
usethisidiom:
classC(object):
@staticmethod
deff(arg1,arg2,...):
...
22/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
Changedinversion2.4:Functiondecoratorsyntaxadded.
class str (object='')
Returnastringcontaininganicelyprintablerepresentationofanobject.Forstrings,this
returns the string itself. The difference with repr(object) is that str(object) does not
always attempt to return a string that is acceptable to eval() its goal is to return a
printablestring.Ifnoargumentisgiven,returnstheemptystring, '' .
For more information on strings see Sequence Types str, unicode, list, tuple,
bytearray, buffer, xrange which describes sequence functionality (strings are
sequences), and also the stringspecific methods described in the String Methods
section.Tooutputformattedstringsusetemplatestringsorthe % operatordescribedin
the String Formatting Operations section. In addition see the String Services section.
Seealso unicode() .
sum (iterable[,start])
Sums start and the items of an iterable from left to right and returns the total. start
defaults to 0 . The iterables items are normally numbers, and the start value is not
allowedtobeastring.
For some use cases, there are good alternatives to sum() . The preferred, fast way to
concatenateasequenceofstringsisbycalling ''.join(sequence) .To add floating point
values with extended precision, see math.fsum() . To concatenate a series of iterables,
considerusing itertools.chain() .
Newinversion2.3.
super (type[,objectortype])
Returnaproxyobjectthat delegatesmethodcallstoa parent orsiblingclassof type.
Thisisusefulforaccessinginheritedmethodsthathavebeenoverriddeninaclass.The
searchorderissameasthatusedby getattr() exceptthatthetypeitselfisskipped.
23/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
programminglanguages.
The second use case is to support cooperative multiple inheritance in a dynamic
executionenvironment.ThisusecaseisuniquetoPythonandisnotfoundinstatically
compiled languages or languages that only support single inheritance. This makes it
possibletoimplementdiamonddiagramswheremultiplebaseclassesimplementthe
samemethod.Gooddesigndictatesthatthismethodhavethesamecallingsignaturein
every case (because the order of calls is determined at runtime, because that order
adapts to changes in the class hierarchy, and because that order can include sibling
classesthatareunknownpriortoruntime).
Forbothusecases,atypicalsuperclasscalllookslikethis:
classC(B):
defmethod(self,arg):
super(C,self).method(arg)
Note that super() is implemented as part of the binding process for explicit dotted
attributelookupssuchas super().__getitem__(name) .Itdoessobyimplementingitsown
__getattribute__() method for searching classes in a predictable order that supports
cooperative multiple inheritance. Accordingly, super() is undefined for implicit lookups
usingstatementsoroperatorssuchas super()[name] .
Also note that super() is not limited to use inside methods. The two argument form
specifiestheargumentsexactlyandmakestheappropriatereferences.
For practical suggestions on how to design cooperative classes using
guidetousingsuper().
super() ,
see
Newinversion2.2.
tuple ([iterable])
Return a tuple whose items are the same and in the same order as iterables items.
iterablemaybeasequence,acontainerthatsupportsiteration,oraniteratorobject.If
iterable is already a tuple, it is returned unchanged. For instance, tuple('abc') returns
('a','b','c') and tuple([1,2,3]) returns (1,2,3) .Ifnoargumentisgiven,returnsa
newemptytuple, () .
tuple
24/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
With three arguments, return a new type object. This is essentially a dynamic form of
the class statement. The name string is the class name and becomes the __name__
attribute the bases tuple itemizes the base classes and becomes the __bases__
attributeandthedictdictionaryisthenamespacecontainingdefinitionsforclassbody
and becomes the __dict__ attribute. For example, the following two statements create
identical type objects:
>>>classX(object):
...a=1
...
>>>X=type('X',(object,),dict(a=1))
>>>
Newinversion2.2.
unichr (i)
Return the Unicode string of one character whose Unicode code is the integer i. For
example, unichr(97) returns the string u'a' . This is the inverse of ord() for Unicode
strings.ThevalidrangefortheargumentdependshowPythonwasconfigureditmay
beeitherUCS2[0..0xFFFF]orUCS4[0..0x10FFFF]. ValueError israisedotherwise.For
ASCIIand8bitstringssee chr() .
Newinversion2.0.
unicode (object='')
unicode (object[,encoding[,errors]])
ReturntheUnicodestringversionofobjectusingoneofthefollowingmodes:
25/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
For more information on Unicode strings see Sequence Types str, unicode, list,
tuple,bytearray,buffer,xrangewhichdescribessequencefunctionality(Unicodestrings
are sequences), and also the stringspecific methods described in the String Methods
section.Tooutputformattedstringsusetemplatestringsorthe % operatordescribedin
the String Formatting Operations section. In addition see the String Services section.
Seealso str() .
Newinversion2.0.
Changedinversion2.2:Supportfor __unicode__() added.
vars ([object])
Return the __dict__ attribute for a module, class, instance, or any other object with a
__dict__ attribute.
zip ([iterable,...])
Thisfunctionreturnsalistoftuples,wheretheithtuplecontainstheithelementfrom
eachoftheargumentsequencesoriterables.Thereturnedlististruncatedinlengthto
https://docs.python.org/2/library/functions.html#builtinfuncs
26/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
the length of the shortest argument sequence. When there are multiple arguments
whichareallofthesamelength, zip() issimilarto map() withaninitialargumentof None .
With a single sequence argument, it returns a list of 1tuples. With no arguments, it
returnsanemptylist.
Thelefttorightevaluationorderoftheiterablesisguaranteed.Thismakespossiblean
idiomforclusteringadataseriesintonlengthgroupsusing zip(*[iter(s)]*n) .
zip() inconjunctionwiththe * operatorcanbeusedtounzipalist:
>>>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
>>>
Newinversion2.0.
Changed in version 2.4: Formerly, zip() required at least one argument and
raiseda TypeError insteadofreturninganemptylist.
zip()
__import__ (name[,globals[,locals[,fromlist[,level]]]])
27/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
whenanonemptyfromlistargumentisgiven,themodulenamedbynameisreturned.
For example, the statement import spam results in bytecode resembling the following
code:
spam=__import__('spam',globals(),locals(),[],1)
28/29
1/2/2015
2.BuiltinFunctionsPython2.7.9documentation
apply()
is equivalent to
function(*args,
Changedinversion2.3:Internedstringsarenotimmortal(liketheyusedtobeinPython
2.2 and before) you must keep a reference to the return value of intern() around to
benefitfromit.
Footnotes
[1] Itisusedrelativelyrarelysodoesnotwarrantbeingmadeintoastatement.
[2] Specifyingabuffersizecurrentlyhasnoeffectonsystemsthatdonthave setvbuf() .
Theinterfacetospecifythebuffersizeisnotdoneusingamethodthatcalls setvbuf() ,
becausethatmaydumpcorewhencalledafteranyI/Ohasbeenperformed,and
theresnoreliablewaytodeterminewhetherthisisthecase.
[3] Inthecurrentimplementation,localvariablebindingscannotnormallybeaffectedthis
way,butvariablesretrievedfromotherscopes(suchasmodules)canbe.Thismay
change.
https://docs.python.org/2/library/functions.html#builtinfuncs
29/29