import struct >>> dir() # show the names in the module namespace ... Since printed arguments are converted to text strings, print() cannot ...
Navigation
index
modules|
next|
previous|
Python»
3.10.4Documentation»
ThePythonStandardLibrary»
Built-inFunctions
|
Built-inFunctions¶
ThePythoninterpreterhasanumberoffunctionsandtypesbuiltintoitthat
arealwaysavailable.Theyarelistedhereinalphabeticalorder.
A
abs()
aiter()
all()
any()
anext()
ascii()
B
bin()
bool()
breakpoint()
bytearray()
bytes()
C
callable()
chr()
classmethod()
compile()
complex()
D
delattr()
dict()
dir()
divmod()
E
enumerate()
eval()
exec()
F
filter()
float()
format()
frozenset()
G
getattr()
globals()
H
hasattr()
hash()
help()
hex()
I
id()
input()
int()
isinstance()
issubclass()
iter()
L
len()
list()
locals()
M
map()
max()
memoryview()
min()
N
next()
O
object()
oct()
open()
ord()
P
pow()
print()
property()
R
range()
repr()
reversed()
round()
S
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
T
tuple()
type()
V
vars()
Z
zip()
_
__import__()
abs(x)¶
Returntheabsolutevalueofanumber.Theargumentmaybean
integer,afloatingpointnumber,oranobjectimplementing__abs__().
Iftheargumentisacomplexnumber,itsmagnitudeisreturned.
aiter(async_iterable)¶
Returnanasynchronousiteratorforanasynchronousiterable.
Equivalenttocallingx.__aiter__().
Note:Unlikeiter(),aiter()hasno2-argumentvariant.
Newinversion3.10.
all(iterable)¶
ReturnTrueifallelementsoftheiterablearetrue(oriftheiterable
isempty).Equivalentto:
defall(iterable):
forelementiniterable:
ifnotelement:
returnFalse
returnTrue
awaitableanext(async_iterator[,default])¶
Whenawaited,returnthenextitemfromthegivenasynchronous
iterator,ordefaultifgivenandtheiteratorisexhausted.
Thisistheasyncvariantofthenext()builtin,andbehaves
similarly.
Thiscallsthe__anext__()methodofasync_iterator,
returninganawaitable.Awaitingthisreturnsthenextvalueofthe
iterator.Ifdefaultisgiven,itisreturnediftheiteratorisexhausted,
otherwiseStopAsyncIterationisraised.
Newinversion3.10.
any(iterable)¶
ReturnTrueifanyelementoftheiterableistrue.Iftheiterable
isempty,returnFalse.Equivalentto:
defany(iterable):
forelementiniterable:
ifelement:
returnTrue
returnFalse
ascii(object)¶
Asrepr(),returnastringcontainingaprintablerepresentationofan
object,butescapethenon-ASCIIcharactersinthestringreturnedby
repr()using\x,\u,or\Uescapes.Thisgeneratesastring
similartothatreturnedbyrepr()inPython2.
bin(x)¶
Convertanintegernumbertoabinarystringprefixedwith“0b”.Theresult
isavalidPythonexpression.IfxisnotaPythonintobject,it
hastodefinean__index__()methodthatreturnsaninteger.Some
examples:
>>>bin(3)
'0b11'
>>>bin(-10)
'-0b1010'
Iftheprefix“0b”isdesiredornot,youcanuseeitherofthefollowingways.
>>>format(14,'#b'),format(14,'b')
('0b1110','1110')
>>>f'{14:#b}',f'{14:b}'
('0b1110','1110')
Seealsoformat()formoreinformation.
classbool([x])¶
ReturnaBooleanvalue,i.e.oneofTrueorFalse.xisconverted
usingthestandardtruthtestingprocedure.Ifxisfalse
oromitted,thisreturnsFalse;otherwise,itreturnsTrue.The
boolclassisasubclassofint(seeNumericTypes—int,float,complex).
Itcannotbesubclassedfurther.ItsonlyinstancesareFalseand
True(seeBooleanValues).
Changedinversion3.7:xisnowapositional-onlyparameter.
breakpoint(*args,**kws)¶
Thisfunctiondropsyouintothedebuggeratthecallsite.Specifically,
itcallssys.breakpointhook(),passingargsandkwsstraight
through.Bydefault,sys.breakpointhook()calls
pdb.set_trace()expectingnoarguments.Inthiscase,itis
purelyaconveniencefunctionsoyoudon’thavetoexplicitlyimport
pdbortypeasmuchcodetoenterthedebugger.However,
sys.breakpointhook()canbesettosomeotherfunctionand
breakpoint()willautomaticallycallthat,allowingyoutodropinto
thedebuggerofchoice.
Raisesanauditingeventbuiltins.breakpointwithargumentbreakpointhook.
Newinversion3.7.
classbytearray([source[,encoding[,errors]]])
Returnanewarrayofbytes.Thebytearrayclassisamutable
sequenceofintegersintherange0<=x<256.Ithasmostoftheusual
methodsofmutablesequences,describedinMutableSequenceTypes,aswell
asmostmethodsthatthebytestypehas,seeBytesandBytearrayOperations.
Theoptionalsourceparametercanbeusedtoinitializethearrayinafew
differentways:
Ifitisastring,youmustalsogivetheencoding(andoptionally,
errors)parameters;bytearray()thenconvertsthestringto
bytesusingstr.encode().
Ifitisaninteger,thearraywillhavethatsizeandwillbe
initializedwithnullbytes.
Ifitisanobjectconformingtothebufferinterface,
aread-onlybufferoftheobjectwillbeusedtoinitializethebytesarray.
Ifitisaniterable,itmustbeaniterableofintegersintherange
0<=x<256,whichareusedastheinitialcontentsofthearray.
Withoutanargument,anarrayofsize0iscreated.
SeealsoBinarySequenceTypes—bytes,bytearray,memoryviewandBytearrayObjects.
classbytes([source[,encoding[,errors]]])
Returnanew“bytes”objectwhichisanimmutablesequenceofintegersin
therange0<=x<256.bytesisanimmutableversionof
bytearray–ithasthesamenon-mutatingmethodsandthesame
indexingandslicingbehavior.
Accordingly,constructorargumentsareinterpretedasforbytearray().
Bytesobjectscanalsobecreatedwithliterals,seeStringandBytesliterals.
SeealsoBinarySequenceTypes—bytes,bytearray,memoryview,BytesObjects,andBytesandBytearrayOperations.
callable(object)¶
ReturnTrueiftheobjectargumentappearscallable,
Falseifnot.IfthisreturnsTrue,itisstillpossiblethata
callfails,butifitisFalse,callingobjectwillneversucceed.
Notethatclassesarecallable(callingaclassreturnsanewinstance);
instancesarecallableiftheirclasshasa__call__()method.
Newinversion3.2:ThisfunctionwasfirstremovedinPython3.0andthenbroughtback
inPython3.2.
chr(i)¶
ReturnthestringrepresentingacharacterwhoseUnicodecodepointisthe
integeri.Forexample,chr(97)returnsthestring'a',while
chr(8364)returnsthestring'€'.Thisistheinverseoford().
Thevalidrangefortheargumentisfrom0through1,114,111(0x10FFFFin
base16).ValueErrorwillberaisedifiisoutsidethatrange.
@classmethod¶
Transformamethodintoaclassmethod.
Aclassmethodreceivestheclassasanimplicitfirstargument,justlikean
instancemethodreceivestheinstance.Todeclareaclassmethod,usethis
idiom:
classC:
@classmethod
deff(cls,arg1,arg2):...
The@classmethodformisafunctiondecorator–see
Functiondefinitionsfordetails.
Aclassmethodcanbecalledeitherontheclass(suchasC.f())oronaninstance(such
asC().f()).Theinstanceisignoredexceptforitsclass.Ifaclass
methodiscalledforaderivedclass,thederivedclassobjectispassedasthe
impliedfirstargument.
ClassmethodsaredifferentthanC++orJavastaticmethods.Ifyouwantthose,
seestaticmethod()inthissection.
Formoreinformationonclassmethods,seeThestandardtypehierarchy.
Changedinversion3.9:Classmethodscannowwrapotherdescriptorssuchas
property().
Changedinversion3.10:Classmethodsnowinheritthemethodattributes(__module__,
__name__,__qualname__,__doc__and__annotations__)and
haveanew__wrapped__attribute.
compile(source,filename,mode,flags=0,dont_inherit=False,optimize=-1)¶
CompilethesourceintoacodeorASTobject.Codeobjectscanbeexecuted
byexec()oreval().sourcecaneitherbeanormalstring,a
bytestring,oranASTobject.Refertotheastmoduledocumentation
forinformationonhowtoworkwithASTobjects.
Thefilenameargumentshouldgivethefilefromwhichthecodewasread;
passsomerecognizablevalueifitwasn’treadfromafile(''is
commonlyused).
Themodeargumentspecifieswhatkindofcodemustbecompiled;itcanbe
'exec'ifsourceconsistsofasequenceofstatements,'eval'ifit
consistsofasingleexpression,or'single'ifitconsistsofasingle
interactivestatement(inthelattercase,expressionstatementsthat
evaluatetosomethingotherthanNonewillbeprinted).
Theoptionalargumentsflagsanddont_inheritcontrolwhich
compileroptionsshouldbeactivated
andwhichfuturefeaturesshouldbeallowed.Ifneither
ispresent(orbotharezero)thecodeiscompiledwiththesameflagsthat
affectthecodethatiscallingcompile().Iftheflags
argumentisgivenanddont_inheritisnot(oriszero)thenthecompiler
optionsandthefuturestatementsspecifiedbytheflagsargumentareused
inadditiontothosethatwouldbeusedanyway.Ifdont_inheritisa
non-zerointegerthentheflagsargumentisit–theflags(future
featuresandcompileroptions)inthesurroundingcodeareignored.
Compileroptionsandfuturestatementsarespecifiedbybitswhichcanbe
bitwiseORedtogethertospecifymultipleoptions.Thebitfieldrequiredto
specifyagivenfuturefeaturecanbefoundasthe
compiler_flagattributeonthe
_Featureinstanceinthe__future__module.
Compilerflagscanbefoundinast
module,withPyCF_prefix.
Theargumentoptimizespecifiestheoptimizationlevelofthecompiler;the
defaultvalueof-1selectstheoptimizationleveloftheinterpreteras
givenby-Ooptions.Explicitlevelsare0(nooptimization;
__debug__istrue),1(assertsareremoved,__debug__isfalse)
or2(docstringsareremovedtoo).
ThisfunctionraisesSyntaxErrorifthecompiledsourceisinvalid,
andValueErrorifthesourcecontainsnullbytes.
IfyouwanttoparsePythoncodeintoitsASTrepresentation,see
ast.parse().
Raisesanauditingeventcompilewitharguments
sourceandfilename.Thiseventmayalsoberaisedbyimplicit
compilation.
Note
Whencompilingastringwithmulti-linecodein'single'or
'eval'mode,inputmustbeterminatedbyatleastonenewline
character.Thisistofacilitatedetectionofincompleteandcomplete
statementsinthecodemodule.
Warning
ItispossibletocrashthePythoninterpreterwitha
sufficientlylarge/complexstringwhencompilingtoanAST
objectduetostackdepthlimitationsinPython’sASTcompiler.
Changedinversion3.2:AlloweduseofWindowsandMacnewlines.Also,inputin'exec'mode
doesnothavetoendinanewlineanymore.Addedtheoptimizeparameter.
Changedinversion3.5:Previously,TypeErrorwasraisedwhennullbyteswereencountered
insource.
Newinversion3.8:ast.PyCF_ALLOW_TOP_LEVEL_AWAITcannowbepassedinflagstoenable
supportfortop-levelawait,asyncfor,andasyncwith.
classcomplex([real[,imag]])¶
Returnacomplexnumberwiththevaluereal+imag*1jorconvertastring
ornumbertoacomplexnumber.Ifthefirstparameterisastring,itwill
beinterpretedasacomplexnumberandthefunctionmustbecalledwithouta
secondparameter.Thesecondparametercanneverbeastring.Eachargument
maybeanynumerictype(includingcomplex).Ifimagisomitted,it
defaultstozeroandtheconstructorservesasanumericconversionlike
intandfloat.Ifbothargumentsareomitted,returns
0j.
ForageneralPythonobjectx,complex(x)delegatesto
x.__complex__().If__complex__()isnotdefinedthenitfallsback
to__float__().If__float__()isnotdefinedthenitfallsback
to__index__().
Note
Whenconvertingfromastring,thestringmustnotcontainwhitespace
aroundthecentral+or-operator.Forexample,
complex('1+2j')isfine,butcomplex('1+2j')raises
ValueError.
ThecomplextypeisdescribedinNumericTypes—int,float,complex.
Changedinversion3.6:Groupingdigitswithunderscoresasincodeliteralsisallowed.
Changedinversion3.8:Fallsbackto__index__()if__complex__()and
__float__()arenotdefined.
delattr(object,name)¶
Thisisarelativeofsetattr().Theargumentsareanobjectanda
string.Thestringmustbethenameofoneoftheobject’sattributes.The
functiondeletesthenamedattribute,providedtheobjectallowsit.For
example,delattr(x,'foobar')isequivalenttodelx.foobar.
classdict(**kwarg)
classdict(mapping,**kwarg)
classdict(iterable,**kwarg)
Createanewdictionary.Thedictobjectisthedictionaryclass.
SeedictandMappingTypes—dictfordocumentationaboutthisclass.
Forothercontainersseethebuilt-inlist,set,and
tupleclasses,aswellasthecollectionsmodule.
dir([object])¶
Withoutarguments,returnthelistofnamesinthecurrentlocalscope.Withan
argument,attempttoreturnalistofvalidattributesforthatobject.
Iftheobjecthasamethodnamed__dir__(),thismethodwillbecalledand
mustreturnthelistofattributes.Thisallowsobjectsthatimplementacustom
__getattr__()or__getattribute__()functiontocustomizetheway
dir()reportstheirattributes.
Iftheobjectdoesnotprovide__dir__(),thefunctiontriesitsbestto
gatherinformationfromtheobject’s__dict__attribute,ifdefined,and
fromitstypeobject.Theresultinglistisnotnecessarilycompleteandmay
beinaccuratewhentheobjecthasacustom__getattr__().
Thedefaultdir()mechanismbehavesdifferentlywithdifferenttypesof
objects,asitattemptstoproducethemostrelevant,ratherthancomplete,
information:
Iftheobjectisamoduleobject,thelistcontainsthenamesofthemodule’s
attributes.
Iftheobjectisatypeorclassobject,thelistcontainsthenamesofits
attributes,andrecursivelyoftheattributesofitsbases.
Otherwise,thelistcontainstheobject’sattributes’names,thenamesofits
class’sattributes,andrecursivelyoftheattributesofitsclass’sbase
classes.
Theresultinglistissortedalphabetically.Forexample:
>>>importstruct
>>>dir()#showthenamesinthemodulenamespace
['__builtins__','__name__','struct']
>>>dir(struct)#showthenamesinthestructmodule
['Struct','__all__','__builtins__','__cached__','__doc__','__file__',
'__initializing__','__loader__','__name__','__package__',
'_clearcache','calcsize','error','pack','pack_into',
'unpack','unpack_from']
>>>classShape:
...def__dir__(self):
...return['area','perimeter','location']
>>>s=Shape()
>>>dir(s)
['area','location','perimeter']
Note
Becausedir()issuppliedprimarilyasaconvenienceforuseatan
interactiveprompt,ittriestosupplyaninterestingsetofnamesmore
thanittriestosupplyarigorouslyorconsistentlydefinedsetofnames,
anditsdetailedbehaviormaychangeacrossreleases.Forexample,
metaclassattributesarenotintheresultlistwhentheargumentisa
class.
divmod(a,b)¶
Taketwo(non-complex)numbersasargumentsandreturnapairofnumbers
consistingoftheirquotientandremainderwhenusingintegerdivision.With
mixedoperandtypes,therulesforbinaryarithmeticoperatorsapply.For
integers,theresultisthesameas(a//b,a%b).Forfloatingpoint
numberstheresultis(q,a%b),whereqisusuallymath.floor(a/
b)butmaybe1lessthanthat.Inanycaseq*b+a%bisvery
closetoa,ifa%bisnon-zeroithasthesamesignasb,and0
<=abs(a%b)>>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')]
Equivalentto:
defenumerate(sequence,start=0):
n=start
foreleminsequence:
yieldn,elem
n+=1
eval(expression[,globals[,locals]])¶
Theargumentsareastringandoptionalglobalsandlocals.Ifprovided,
globalsmustbeadictionary.Ifprovided,localscanbeanymapping
object.
TheexpressionargumentisparsedandevaluatedasaPythonexpression
(technicallyspeaking,aconditionlist)usingtheglobalsandlocals
dictionariesasglobalandlocalnamespace.Iftheglobalsdictionaryis
presentanddoesnotcontainavalueforthekey__builtins__,a
referencetothedictionaryofthebuilt-inmodulebuiltinsis
insertedunderthatkeybeforeexpressionisparsed.Thatwayyoucan
controlwhatbuiltinsareavailabletotheexecutedcodebyinsertingyour
own__builtins__dictionaryintoglobalsbeforepassingitto
eval().Ifthelocalsdictionaryisomitteditdefaultstothe
globalsdictionary.Ifbothdictionariesareomitted,theexpressionis
executedwiththeglobalsandlocalsintheenvironmentwhere
eval()iscalled.Note,eval()doesnothaveaccesstothe
nestedscopes(non-locals)intheenclosing
environment.
Thereturnvalueistheresultof
theevaluatedexpression.Syntaxerrorsarereportedasexceptions.Example:
>>>x=1
>>>eval('x+1')
2
Thisfunctioncanalsobeusedtoexecutearbitrarycodeobjects(suchas
thosecreatedbycompile()).Inthiscase,passacodeobjectinstead
ofastring.Ifthecodeobjecthasbeencompiledwith'exec'asthe
modeargument,eval()'sreturnvaluewillbeNone.
Hints:dynamicexecutionofstatementsissupportedbytheexec()
function.Theglobals()andlocals()functions
returnthecurrentglobalandlocaldictionary,respectively,whichmaybe
usefultopassaroundforusebyeval()orexec().
Ifthegivensourceisastring,thenleadingandtrailingspacesandtabs
arestripped.
Seeast.literal_eval()forafunctionthatcansafelyevaluatestrings
withexpressionscontainingonlyliterals.
Raisesanauditingeventexecwiththecodeobject
astheargument.Codecompilationeventsmayalsoberaised.
exec(object[,globals[,locals]])¶
ThisfunctionsupportsdynamicexecutionofPythoncode.objectmustbe
eitherastringoracodeobject.Ifitisastring,thestringisparsedas
asuiteofPythonstatementswhichisthenexecuted(unlessasyntaxerror
occurs).1Ifitisacodeobject,itissimplyexecuted.Inallcases,
thecodethat’sexecutedisexpectedtobevalidasfileinput(seethe
sectionFileinputintheReferenceManual).Beawarethatthe
nonlocal,yield,andreturn
statementsmaynotbeusedoutsideof
functiondefinitionsevenwithinthecontextofcodepassedtothe
exec()function.ThereturnvalueisNone.
Inallcases,iftheoptionalpartsareomitted,thecodeisexecutedinthe
currentscope.Ifonlyglobalsisprovided,itmustbeadictionary
(andnotasubclassofdictionary),which
willbeusedforboththeglobalandthelocalvariables.Ifglobalsand
localsaregiven,theyareusedfortheglobalandlocalvariables,
respectively.Ifprovided,localscanbeanymappingobject.Remember
thatatthemodulelevel,globalsandlocalsarethesamedictionary.Ifexec
getstwoseparateobjectsasglobalsandlocals,thecodewillbe
executedasifitwereembeddedinaclassdefinition.
Iftheglobalsdictionarydoesnotcontainavalueforthekey
__builtins__,areferencetothedictionaryofthebuilt-inmodule
builtinsisinsertedunderthatkey.Thatwayyoucancontrolwhat
builtinsareavailabletotheexecutedcodebyinsertingyourown
__builtins__dictionaryintoglobalsbeforepassingittoexec().
Raisesanauditingeventexecwiththecodeobject
astheargument.Codecompilationeventsmayalsoberaised.
Note
Thebuilt-infunctionsglobals()andlocals()returnthecurrent
globalandlocaldictionary,respectively,whichmaybeusefultopassaround
foruseasthesecondandthirdargumenttoexec().
Note
Thedefaultlocalsactasdescribedforfunctionlocals()below:
modificationstothedefaultlocalsdictionaryshouldnotbeattempted.
Passanexplicitlocalsdictionaryifyouneedtoseeeffectsofthe
codeonlocalsafterfunctionexec()returns.
filter(function,iterable)¶
Constructaniteratorfromthoseelementsofiterableforwhichfunction
returnstrue.iterablemaybeeitherasequence,acontainerwhich
supportsiteration,oraniterator.IffunctionisNone,theidentity
functionisassumed,thatis,allelementsofiterablethatarefalseare
removed.
Notethatfilter(function,iterable)isequivalenttothegenerator
expression(itemforiteminiterableiffunction(item))iffunctionis
notNoneand(itemforiteminiterableifitem)iffunctionis
None.
Seeitertools.filterfalse()forthecomplementaryfunctionthatreturns
elementsofiterableforwhichfunctionreturnsfalse.
classfloat([x])¶
Returnafloatingpointnumberconstructedfromanumberorstringx.
Iftheargumentisastring,itshouldcontainadecimalnumber,optionally
precededbyasign,andoptionallyembeddedinwhitespace.Theoptional
signmaybe'+'or'-';a'+'signhasnoeffectonthevalue
produced.TheargumentmayalsobeastringrepresentingaNaN
(not-a-number),orpositiveornegativeinfinity.Moreprecisely,the
inputmustconformtothefollowinggrammarafterleadingandtrailing
whitespacecharactersareremoved:
sign::="+"|"-"
infinity::="Infinity"|"inf"
nan::="nan"
numeric_value::=floatnumber|infinity|nan
numeric_string::=[sign]numeric_value
HerefloatnumberistheformofaPythonfloating-pointliteral,
describedinFloatingpointliterals.Caseisnotsignificant,so,forexample,
“inf”,“Inf”,“INFINITY”,and“iNfINity”areallacceptablespellingsfor
positiveinfinity.
Otherwise,iftheargumentisanintegerorafloatingpointnumber,a
floatingpointnumberwiththesamevalue(withinPython’sfloatingpoint
precision)isreturned.IftheargumentisoutsidetherangeofaPython
float,anOverflowErrorwillberaised.
ForageneralPythonobjectx,float(x)delegatesto
x.__float__().If__float__()isnotdefinedthenitfallsback
to__index__().
Ifnoargumentisgiven,0.0isreturned.
Examples:
>>>float('+1.23')
1.23
>>>float('-12345\n')
-12345.0
>>>float('1e-003')
0.001
>>>float('+1E6')
1000000.0
>>>float('-Infinity')
-inf
ThefloattypeisdescribedinNumericTypes—int,float,complex.
Changedinversion3.6:Groupingdigitswithunderscoresasincodeliteralsisallowed.
Changedinversion3.7:xisnowapositional-onlyparameter.
Changedinversion3.8:Fallsbackto__index__()if__float__()isnotdefined.
format(value[,format_spec])¶
Convertavaluetoa“formatted”representation,ascontrolledby
format_spec.Theinterpretationofformat_specwilldependonthetype
ofthevalueargument;however,thereisastandardformattingsyntaxthat
isusedbymostbuilt-intypes:FormatSpecificationMini-Language.
Thedefaultformat_specisanemptystringwhichusuallygivesthesame
effectascallingstr(value).
Acalltoformat(value,format_spec)istranslatedto
type(value).__format__(value,format_spec)whichbypassestheinstance
dictionarywhensearchingforthevalue’s__format__()method.A
TypeErrorexceptionisraisedifthemethodsearchreaches
objectandtheformat_specisnon-empty,orifeitherthe
format_specorthereturnvaluearenotstrings.
Changedinversion3.4:object().__format__(format_spec)raisesTypeError
ifformat_specisnotanemptystring.
classfrozenset([iterable])
Returnanewfrozensetobject,optionallywithelementstakenfrom
iterable.frozensetisabuilt-inclass.Seefrozensetand
SetTypes—set,frozensetfordocumentationaboutthisclass.
Forothercontainersseethebuilt-inset,list,
tuple,anddictclasses,aswellasthecollections
module.
getattr(object,name[,default])¶
Returnthevalueofthenamedattributeofobject.namemustbeastring.
Ifthestringisthenameofoneoftheobject’sattributes,theresultisthe
valueofthatattribute.Forexample,getattr(x,'foobar')isequivalentto
x.foobar.Ifthenamedattributedoesnotexist,defaultisreturnedif
provided,otherwiseAttributeErrorisraised.
Note
Sinceprivatenamemanglinghappensat
compilationtime,onemustmanuallymangleaprivateattribute’s
(attributeswithtwoleadingunderscores)nameinordertoretrieveitwith
getattr().
globals()¶
Returnthedictionaryimplementingthecurrentmodulenamespace.Forcodewithin
functions,thisissetwhenthefunctionisdefinedandremainsthesame
regardlessofwherethefunctioniscalled.
hasattr(object,name)¶
Theargumentsareanobjectandastring.TheresultisTrueifthe
stringisthenameofoneoftheobject’sattributes,Falseifnot.(This
isimplementedbycallinggetattr(object,name)andseeingwhetherit
raisesanAttributeErrorornot.)
hash(object)¶
Returnthehashvalueoftheobject(ifithasone).Hashvaluesare
integers.Theyareusedtoquicklycomparedictionarykeysduringa
dictionarylookup.Numericvaluesthatcompareequalhavethesamehash
value(eveniftheyareofdifferenttypes,asisthecasefor1and1.0).
Note
Forobjectswithcustom__hash__()methods,notethathash()
truncatesthereturnvaluebasedonthebitwidthofthehostmachine.
See__hash__()fordetails.
help([object])¶
Invokethebuilt-inhelpsystem.(Thisfunctionisintendedforinteractive
use.)Ifnoargumentisgiven,theinteractivehelpsystemstartsonthe
interpreterconsole.Iftheargumentisastring,thenthestringislookedup
asthenameofamodule,function,class,method,keyword,ordocumentation
topic,andahelppageisprintedontheconsole.Iftheargumentisanyother
kindofobject,ahelppageontheobjectisgenerated.
Notethatifaslash(/)appearsintheparameterlistofafunctionwhen
invokinghelp(),itmeansthattheparameterspriortotheslashare
positional-only.Formoreinfo,see
theFAQentryonpositional-onlyparameters.
Thisfunctionisaddedtothebuilt-innamespacebythesitemodule.
Changedinversion3.4:Changestopydocandinspectmeanthatthereported
signaturesforcallablesarenowmorecomprehensiveandconsistent.
hex(x)¶
Convertanintegernumbertoalowercasehexadecimalstringprefixedwith
“0x”.IfxisnotaPythonintobject,ithastodefinean
__index__()methodthatreturnsaninteger.Someexamples:
>>>hex(255)
'0xff'
>>>hex(-42)
'-0x2a'
Ifyouwanttoconvertanintegernumbertoanuppercaseorlowerhexadecimal
stringwithprefixornot,youcanuseeitherofthefollowingways:
>>>'%#x'%255,'%x'%255,'%X'%255
('0xff','ff','FF')
>>>format(255,'#x'),format(255,'x'),format(255,'X')
('0xff','ff','FF')
>>>f'{255:#x}',f'{255:x}',f'{255:X}'
('0xff','ff','FF')
Seealsoformat()formoreinformation.
Seealsoint()forconvertingahexadecimalstringtoan
integerusingabaseof16.
Note
Toobtainahexadecimalstringrepresentationforafloat,usethe
float.hex()method.
id(object)¶
Returnthe“identity”ofanobject.Thisisanintegerwhich
isguaranteedtobeuniqueandconstantforthisobjectduringitslifetime.
Twoobjectswithnon-overlappinglifetimesmayhavethesameid()
value.
CPythonimplementationdetail:Thisistheaddressoftheobjectinmemory.
Raisesanauditingeventbuiltins.idwithargumentid.
input([prompt])¶
Ifthepromptargumentispresent,itiswrittentostandardoutputwithout
atrailingnewline.Thefunctionthenreadsalinefrominput,convertsit
toastring(strippingatrailingnewline),andreturnsthat.WhenEOFis
read,EOFErrorisraised.Example:
>>>s=input('-->')
-->MontyPython'sFlyingCircus
>>>s
"MontyPython'sFlyingCircus"
Ifthereadlinemodulewasloaded,theninput()willuseit
toprovideelaboratelineeditingandhistoryfeatures.
Raisesanauditingeventbuiltins.inputwith
argumentpromptbeforereadinginput
Raisesanauditingeventbuiltins.input/resultwiththeresultafter
successfullyreadinginput.
classint([x])¶
classint(x,base=10)
Returnanintegerobjectconstructedfromanumberorstringx,orreturn
0ifnoargumentsaregiven.Ifxdefines__int__(),
int(x)returnsx.__int__().Ifxdefines__index__(),
itreturnsx.__index__().Ifxdefines__trunc__(),
itreturnsx.__trunc__().
Forfloatingpointnumbers,thistruncatestowardszero.
Ifxisnotanumberorifbaseisgiven,thenxmustbeastring,
bytes,orbytearrayinstancerepresentinganinteger
literalinradixbase.Optionally,theliteralcanbe
precededby+or-(withnospaceinbetween)andsurroundedby
whitespace.Abase-nliteralconsistsofthedigits0ton-1,witha
toz(orAtoZ)having
values10to35.Thedefaultbaseis10.Theallowedvaluesare0and2–36.
Base-2,-8,and-16literalscanbeoptionallyprefixedwith0b/0B,
0o/0O,or0x/0X,aswithintegerliteralsincode.Base0
meanstointerpretexactlyasacodeliteral,sothattheactualbaseis2,
8,10,or16,andsothatint('010',0)isnotlegal,while
int('010')is,aswellasint('010',8).
TheintegertypeisdescribedinNumericTypes—int,float,complex.
Changedinversion3.4:Ifbaseisnotaninstanceofintandthebaseobjecthasa
base.__index__method,thatmethodiscalled
toobtainanintegerforthebase.Previousversionsused
base.__int__insteadofbase.__index__.
Changedinversion3.6:Groupingdigitswithunderscoresasincodeliteralsisallowed.
Changedinversion3.7:xisnowapositional-onlyparameter.
Changedinversion3.8:Fallsbackto__index__()if__int__()isnotdefined.
isinstance(object,classinfo)¶
ReturnTrueiftheobjectargumentisaninstanceoftheclassinfo
argument,orofa(direct,indirect,orvirtual)subclassthereof.Ifobjectisnot
anobjectofthegiventype,thefunctionalwaysreturnsFalse.
Ifclassinfoisatupleoftypeobjects(orrecursively,othersuch
tuples)oraUnionTypeofmultipletypes,returnTrueif
objectisaninstanceofanyofthetypes.
Ifclassinfoisnotatypeortupleoftypesandsuchtuples,
aTypeErrorexceptionisraised.
Changedinversion3.10:classinfocanbeaUnionType.
issubclass(class,classinfo)¶
ReturnTrueifclassisasubclass(direct,indirect,orvirtual)ofclassinfo.A
classisconsideredasubclassofitself.classinfomaybeatupleofclass
objectsoraUnionType,inwhichcasereturnTrueifclassisa
subclassofanyentryinclassinfo.Inanyothercase,aTypeError
exceptionisraised.
Changedinversion3.10:classinfocanbeaUnionType.
iter(object[,sentinel])¶
Returnaniteratorobject.Thefirstargumentisinterpretedvery
differentlydependingonthepresenceofthesecondargument.Withouta
secondargument,objectmustbeacollectionobjectwhichsupportsthe
iterableprotocol(the__iter__()method),oritmustsupport
thesequenceprotocol(the__getitem__()methodwithintegerarguments
startingat0).Ifitdoesnotsupporteitherofthoseprotocols,
TypeErrorisraised.Ifthesecondargument,sentinel,isgiven,
thenobjectmustbeacallableobject.Theiteratorcreatedinthiscase
willcallobjectwithnoargumentsforeachcalltoits
__next__()method;ifthevaluereturnedisequalto
sentinel,StopIterationwillberaised,otherwisethevaluewill
bereturned.
SeealsoIteratorTypes.
Oneusefulapplicationofthesecondformofiter()istobuilda
block-reader.Forexample,readingfixed-widthblocksfromabinary
databasefileuntiltheendoffileisreached:
fromfunctoolsimportpartial
withopen('mydata.db','rb')asf:
forblockiniter(partial(f.read,64),b''):
process_block(block)
len(s)¶
Returnthelength(thenumberofitems)ofanobject.Theargumentmaybea
sequence(suchasastring,bytes,tuple,list,orrange)oracollection
(suchasadictionary,set,orfrozenset).
CPythonimplementationdetail:lenraisesOverflowErroronlengthslargerthan
sys.maxsize,suchasrange(2**100).
classlist([iterable])
Ratherthanbeingafunction,listisactuallyamutable
sequencetype,asdocumentedinListsandSequenceTypes—list,tuple,range.
locals()¶
Updateandreturnadictionaryrepresentingthecurrentlocalsymboltable.
Freevariablesarereturnedbylocals()whenitiscalledinfunction
blocks,butnotinclassblocks.Notethatatthemodulelevel,locals()
andglobals()arethesamedictionary.
Note
Thecontentsofthisdictionaryshouldnotbemodified;changesmaynot
affectthevaluesoflocalandfreevariablesusedbytheinterpreter.
map(function,iterable,...)¶
Returnaniteratorthatappliesfunctiontoeveryitemofiterable,
yieldingtheresults.Ifadditionaliterableargumentsarepassed,
functionmusttakethatmanyargumentsandisappliedtotheitemsfromall
iterablesinparallel.Withmultipleiterables,theiteratorstopswhenthe
shortestiterableisexhausted.Forcaseswherethefunctioninputsare
alreadyarrangedintoargumenttuples,seeitertools.starmap().
max(iterable,*[,key,default])¶
max(arg1,arg2,*args[,key])
Returnthelargestiteminaniterableorthelargestoftwoormore
arguments.
Ifonepositionalargumentisprovided,itshouldbeaniterable.
Thelargestitemintheiterableisreturned.Iftwoormorepositional
argumentsareprovided,thelargestofthepositionalargumentsis
returned.
Therearetwooptionalkeyword-onlyarguments.Thekeyargumentspecifies
aone-argumentorderingfunctionlikethatusedforlist.sort().The
defaultargumentspecifiesanobjecttoreturniftheprovidediterableis
empty.Iftheiterableisemptyanddefaultisnotprovided,a
ValueErrorisraised.
Ifmultipleitemsaremaximal,thefunctionreturnsthefirstone
encountered.Thisisconsistentwithothersort-stabilitypreservingtools
suchassorted(iterable,key=keyfunc,reverse=True)[0]and
heapq.nlargest(1,iterable,key=keyfunc).
Newinversion3.4:Thedefaultkeyword-onlyargument.
Changedinversion3.8:ThekeycanbeNone.
classmemoryview(object)
Returna“memoryview”objectcreatedfromthegivenargument.See
MemoryViewsformoreinformation.
min(iterable,*[,key,default])¶
min(arg1,arg2,*args[,key])
Returnthesmallestiteminaniterableorthesmallestoftwoormore
arguments.
Ifonepositionalargumentisprovided,itshouldbeaniterable.
Thesmallestitemintheiterableisreturned.Iftwoormorepositional
argumentsareprovided,thesmallestofthepositionalargumentsis
returned.
Therearetwooptionalkeyword-onlyarguments.Thekeyargumentspecifies
aone-argumentorderingfunctionlikethatusedforlist.sort().The
defaultargumentspecifiesanobjecttoreturniftheprovidediterableis
empty.Iftheiterableisemptyanddefaultisnotprovided,a
ValueErrorisraised.
Ifmultipleitemsareminimal,thefunctionreturnsthefirstone
encountered.Thisisconsistentwithothersort-stabilitypreservingtools
suchassorted(iterable,key=keyfunc)[0]andheapq.nsmallest(1,
iterable,key=keyfunc).
Newinversion3.4:Thedefaultkeyword-onlyargument.
Changedinversion3.8:ThekeycanbeNone.
next(iterator[,default])¶
Retrievethenextitemfromtheiteratorbycallingits
__next__()method.Ifdefaultisgiven,itisreturned
iftheiteratorisexhausted,otherwiseStopIterationisraised.
classobject¶
Returnanewfeaturelessobject.objectisabaseforallclasses.
IthasmethodsthatarecommontoallinstancesofPythonclasses.This
functiondoesnotacceptanyarguments.
Note
objectdoesnothavea__dict__,soyoucan’t
assignarbitraryattributestoaninstanceoftheobjectclass.
oct(x)¶
Convertanintegernumbertoanoctalstringprefixedwith“0o”.Theresult
isavalidPythonexpression.IfxisnotaPythonintobject,it
hastodefinean__index__()methodthatreturnsaninteger.For
example:
>>>oct(8)
'0o10'
>>>oct(-56)
'-0o70'
Ifyouwanttoconvertanintegernumbertoanoctalstringeitherwiththeprefix
“0o”ornot,youcanuseeitherofthefollowingways.
>>>'%#o'%10,'%o'%10
('0o12','12')
>>>format(10,'#o'),format(10,'o')
('0o12','12')
>>>f'{10:#o}',f'{10:o}'
('0o12','12')
Seealsoformat()formoreinformation.
open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)¶
Openfileandreturnacorrespondingfileobject.Ifthefile
cannotbeopened,anOSErrorisraised.See
ReadingandWritingFilesformoreexamplesofhowtousethisfunction.
fileisapath-likeobjectgivingthepathname(absoluteor
relativetothecurrentworkingdirectory)ofthefiletobeopenedoran
integerfiledescriptorofthefiletobewrapped.(Ifafiledescriptoris
given,itisclosedwhenthereturnedI/Oobjectisclosedunlessclosefd
issettoFalse.)
modeisanoptionalstringthatspecifiesthemodeinwhichthefileis
opened.Itdefaultsto'r'whichmeansopenforreadingintextmode.
Othercommonvaluesare'w'forwriting(truncatingthefileifit
alreadyexists),'x'forexclusivecreation,and'a'forappending
(whichonsomeUnixsystems,meansthatallwritesappendtotheendof
thefileregardlessofthecurrentseekposition).Intextmode,if
encodingisnotspecifiedtheencodingusedisplatform-dependent:
locale.getpreferredencoding(False)iscalledtogetthecurrentlocale
encoding.(Forreadingandwritingrawbytesusebinarymodeandleave
encodingunspecified.)Theavailablemodesare:
'r'
openforreading(default)
'w'
openforwriting,truncatingthefilefirst
'x'
openforexclusivecreation,failingifthefilealreadyexists
'a'
openforwriting,appendingtotheendoffileifitexists
'b'
binarymode
't'
textmode(default)
'+'
openforupdating(readingandwriting)
Thedefaultmodeis'r'(openforreadingtext,asynonymof'rt').
Modes'w+'and'w+b'openandtruncatethefile.Modes'r+'
and'r+b'openthefilewithnotruncation.
AsmentionedintheOverview,Pythondistinguishesbetweenbinary
andtextI/O.Filesopenedinbinarymode(including'b'inthemode
argument)returncontentsasbytesobjectswithoutanydecoding.In
textmode(thedefault,orwhen't'isincludedinthemodeargument),
thecontentsofthefilearereturnedasstr,thebyteshavingbeen
firstdecodedusingaplatform-dependentencodingorusingthespecified
encodingifgiven.
Thereisanadditionalmodecharacterpermitted,'U',whichnolonger
hasanyeffect,andisconsidereddeprecated.Itpreviouslyenabled
universalnewlinesintextmode,whichbecamethedefaultbehavior
inPython3.0.Refertothedocumentationofthe
newlineparameterforfurtherdetails.
Note
Pythondoesn’tdependontheunderlyingoperatingsystem’snotionoftext
files;alltheprocessingisdonebyPythonitself,andistherefore
platform-independent.
bufferingisanoptionalintegerusedtosetthebufferingpolicy.Pass0
toswitchbufferingoff(onlyallowedinbinarymode),1toselectline
buffering(onlyusableintextmode),andaninteger>1toindicatethesize
inbytesofafixed-sizechunkbuffer.Notethatspecifyingabuffersizethis
wayappliesforbinarybufferedI/O,butTextIOWrapper(i.e.,filesopened
withmode='r+')wouldhaveanotherbuffering.Todisablebufferingin
TextIOWrapper,considerusingthewrite_throughflagfor
io.TextIOWrapper.reconfigure().Whennobufferingargumentis
given,thedefaultbufferingpolicyworksasfollows:
Binaryfilesarebufferedinfixed-sizechunks;thesizeofthebufferis
chosenusingaheuristictryingtodeterminetheunderlyingdevice’s“block
size”andfallingbackonio.DEFAULT_BUFFER_SIZE.Onmanysystems,
thebufferwilltypicallybe4096or8192byteslong.
“Interactive”textfiles(filesforwhichisatty()
returnsTrue)uselinebuffering.Othertextfilesusethepolicy
describedaboveforbinaryfiles.
encodingisthenameoftheencodingusedtodecodeorencodethefile.
Thisshouldonlybeusedintextmode.Thedefaultencodingisplatform
dependent(whateverlocale.getpreferredencoding()returns),butany
textencodingsupportedbyPython
canbeused.Seethecodecsmodulefor
thelistofsupportedencodings.
errorsisanoptionalstringthatspecifieshowencodinganddecoding
errorsaretobehandled—thiscannotbeusedinbinarymode.
Avarietyofstandarderrorhandlersareavailable
(listedunderErrorHandlers),thoughany
errorhandlingnamethathasbeenregisteredwith
codecs.register_error()isalsovalid.Thestandardnames
include:
'strict'toraiseaValueErrorexceptionifthereis
anencodingerror.ThedefaultvalueofNonehasthesame
effect.
'ignore'ignoreserrors.Notethatignoringencodingerrors
canleadtodataloss.
'replace'causesareplacementmarker(suchas'?')tobeinserted
wherethereismalformeddata.
'surrogateescape'willrepresentanyincorrectbytesaslow
surrogatecodeunitsrangingfromU+DC80toU+DCFF.
Thesesurrogatecodeunitswillthenbeturnedbackinto
thesamebyteswhenthesurrogateescapeerrorhandlerisused
whenwritingdata.Thisisusefulforprocessingfilesinan
unknownencoding.
'xmlcharrefreplace'isonlysupportedwhenwritingtoafile.
Charactersnotsupportedbytheencodingarereplacedwiththe
appropriateXMLcharacterreferencennn;.
'backslashreplace'replacesmalformeddatabyPython’sbackslashed
escapesequences.
'namereplace'(alsoonlysupportedwhenwriting)
replacesunsupportedcharacterswith\N{...}escapesequences.
newlinecontrolshowuniversalnewlinesmodeworks(itonly
appliestotextmode).ItcanbeNone,'','\n','\r',and
'\r\n'.Itworksasfollows:
Whenreadinginputfromthestream,ifnewlineisNone,universal
newlinesmodeisenabled.Linesintheinputcanendin'\n',
'\r',or'\r\n',andthesearetranslatedinto'\n'before
beingreturnedtothecaller.Ifitis'',universalnewlinesmodeis
enabled,butlineendingsarereturnedtothecalleruntranslated.Ifit
hasanyoftheotherlegalvalues,inputlinesareonlyterminatedbythe
givenstring,andthelineendingisreturnedtothecalleruntranslated.
Whenwritingoutputtothestream,ifnewlineisNone,any'\n'
characterswrittenaretranslatedtothesystemdefaultlineseparator,
os.linesep.Ifnewlineis''or'\n',notranslation
takesplace.Ifnewlineisanyoftheotherlegalvalues,any'\n'
characterswrittenaretranslatedtothegivenstring.
IfclosefdisFalseandafiledescriptorratherthanafilenamewas
given,theunderlyingfiledescriptorwillbekeptopenwhenthefileis
closed.IfafilenameisgivenclosefdmustbeTrue(thedefault);
otherwise,anerrorwillberaised.
Acustomopenercanbeusedbypassingacallableasopener.Theunderlying
filedescriptorforthefileobjectisthenobtainedbycallingopenerwith
(file,flags).openermustreturnanopenfiledescriptor(passing
os.openasopenerresultsinfunctionalitysimilartopassing
None).
Thenewlycreatedfileisnon-inheritable.
Thefollowingexampleusesthedir_fdparameterofthe
os.open()functiontoopenafilerelativetoagivendirectory:
>>>importos
>>>dir_fd=os.open('somedir',os.O_RDONLY)
>>>defopener(path,flags):
...returnos.open(path,flags,dir_fd=dir_fd)
...
>>>withopen('spamspam.txt','w',opener=opener)asf:
...print('Thiswillbewrittentosomedir/spamspam.txt',file=f)
...
>>>os.close(dir_fd)#don'tleakafiledescriptor
Thetypeoffileobjectreturnedbytheopen()function
dependsonthemode.Whenopen()isusedtoopenafileinatext
mode('w','r','wt','rt',etc.),itreturnsasubclassof
io.TextIOBase(specificallyio.TextIOWrapper).Whenused
toopenafileinabinarymodewithbuffering,thereturnedclassisa
subclassofio.BufferedIOBase.Theexactclassvaries:inread
binarymode,itreturnsanio.BufferedReader;inwritebinaryand
appendbinarymodes,itreturnsanio.BufferedWriter,andin
read/writemode,itreturnsanio.BufferedRandom.Whenbufferingis
disabled,therawstream,asubclassofio.RawIOBase,
io.FileIO,isreturned.
Seealsothefilehandlingmodules,suchasfileinput,io
(whereopen()isdeclared),os,os.path,tempfile,
andshutil.
Raisesanauditingeventopenwithargumentsfile,mode,flags.
Themodeandflagsargumentsmayhavebeenmodifiedorinferredfrom
theoriginalcall.
Changedinversion3.3:
Theopenerparameterwasadded.
The'x'modewasadded.
IOErrorusedtoberaised,itisnowanaliasofOSError.
FileExistsErrorisnowraisedifthefileopenedinexclusive
creationmode('x')alreadyexists.
Changedinversion3.4:
Thefileisnownon-inheritable.
Deprecatedsinceversion3.4,removedinversion3.10:The'U'mode.
Changedinversion3.5:
Ifthesystemcallisinterruptedandthesignalhandlerdoesnotraisean
exception,thefunctionnowretriesthesystemcallinsteadofraisingan
InterruptedErrorexception(seePEP475fortherationale).
The'namereplace'errorhandlerwasadded.
Changedinversion3.6:
Supportaddedtoacceptobjectsimplementingos.PathLike.
OnWindows,openingaconsolebuffermayreturnasubclassof
io.RawIOBaseotherthanio.FileIO.
ord(c)¶
GivenastringrepresentingoneUnicodecharacter,returnaninteger
representingtheUnicodecodepointofthatcharacter.Forexample,
ord('a')returnstheinteger97andord('€')(Eurosign)
returns8364.Thisistheinverseofchr().
pow(base,exp[,mod])¶
Returnbasetothepowerexp;ifmodispresent,returnbasetothe
powerexp,modulomod(computedmoreefficientlythan
pow(base,exp)%mod).Thetwo-argumentformpow(base,exp)is
equivalenttousingthepoweroperator:base**exp.
Theargumentsmusthavenumerictypes.Withmixedoperandtypes,the
coercionrulesforbinaryarithmeticoperatorsapply.Forint
operands,theresulthasthesametypeastheoperands(aftercoercion)
unlessthesecondargumentisnegative;inthatcase,allargumentsare
convertedtofloatandafloatresultisdelivered.Forexample,pow(10,2)
returns100,butpow(10,-2)returns0.01.Foranegativebaseof
typeintorfloatandanon-integralexponent,acomplex
resultisdelivered.Forexample,pow(-9,0.5)returnsavalueclose
to3j.
Forintoperandsbaseandexp,ifmodispresent,modmust
alsobeofintegertypeandmodmustbenonzero.Ifmodispresentand
expisnegative,basemustberelativelyprimetomod.Inthatcase,
pow(inv_base,-exp,mod)isreturned,whereinv_baseisaninverseto
basemodulomod.
Here’sanexampleofcomputinganinversefor38modulo97:
>>>pow(38,-1,mod=97)
23
>>>23*38%97==1
True
Changedinversion3.8:Forintoperands,thethree-argumentformofpownowallows
thesecondargumenttobenegative,permittingcomputationofmodular
inverses.
Changedinversion3.8:Allowkeywordarguments.Formerly,onlypositionalargumentswere
supported.
print(*objects,sep='',end='\n',file=sys.stdout,flush=False)¶
Printobjectstothetextstreamfile,separatedbysepandfollowed
byend.sep,end,file,andflush,ifpresent,mustbegivenaskeyword
arguments.
Allnon-keywordargumentsareconvertedtostringslikestr()doesand
writtentothestream,separatedbysepandfollowedbyend.Bothsep
andendmustbestrings;theycanalsobeNone,whichmeanstousethe
defaultvalues.Ifnoobjectsaregiven,print()willjustwrite
end.
Thefileargumentmustbeanobjectwithawrite(string)method;ifit
isnotpresentorNone,sys.stdoutwillbeused.Sinceprinted
argumentsareconvertedtotextstrings,print()cannotbeusedwith
binarymodefileobjects.Forthese,usefile.write(...)instead.
Whethertheoutputisbufferedisusuallydeterminedbyfile,butifthe
flushkeywordargumentistrue,thestreamisforciblyflushed.
Changedinversion3.3:Addedtheflushkeywordargument.
classproperty(fget=None,fset=None,fdel=None,doc=None)¶
Returnapropertyattribute.
fgetisafunctionforgettinganattributevalue.fsetisafunction
forsettinganattributevalue.fdelisafunctionfordeletinganattribute
value.Anddoccreatesadocstringfortheattribute.
Atypicaluseistodefineamanagedattributex:
classC:
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.")
IfcisaninstanceofC,c.xwillinvokethegetter,
c.x=valuewillinvokethesetter,anddelc.xthedeleter.
Ifgiven,docwillbethedocstringofthepropertyattribute.Otherwise,the
propertywillcopyfget’sdocstring(ifitexists).Thismakesitpossibleto
createread-onlypropertieseasilyusingproperty()asadecorator:
classParrot:
def__init__(self):
self._voltage=100000
@property
defvoltage(self):
"""Getthecurrentvoltage."""
returnself._voltage
The@propertydecoratorturnsthevoltage()methodintoa“getter”
foraread-onlyattributewiththesamename,anditsetsthedocstringfor
voltageto“Getthecurrentvoltage.”
Apropertyobjecthasgetter,setter,
anddeletermethodsusableasdecoratorsthatcreatea
copyofthepropertywiththecorrespondingaccessorfunctionsettothe
decoratedfunction.Thisisbestexplainedwithanexample:
classC:
def__init__(self):
self._x=None
@property
defx(self):
"""I'mthe'x'property."""
returnself._x
@x.setter
defx(self,value):
self._x=value
@x.deleter
defx(self):
delself._x
Thiscodeisexactlyequivalenttothefirstexample.Besuretogivethe
additionalfunctionsthesamenameastheoriginalproperty(xinthis
case.)
Thereturnedpropertyobjectalsohastheattributesfget,fset,and
fdelcorrespondingtotheconstructorarguments.
Changedinversion3.5:Thedocstringsofpropertyobjectsarenowwriteable.
classrange(stop)
classrange(start,stop[,step])
Ratherthanbeingafunction,rangeisactuallyanimmutable
sequencetype,asdocumentedinRangesandSequenceTypes—list,tuple,range.
repr(object)¶
Returnastringcontainingaprintablerepresentationofanobject.Formany
types,thisfunctionmakesanattempttoreturnastringthatwouldyieldan
objectwiththesamevaluewhenpassedtoeval();otherwise,the
representationisastringenclosedinanglebracketsthatcontainsthename
ofthetypeoftheobjecttogetherwithadditionalinformationoften
includingthenameandaddressoftheobject.Aclasscancontrolwhatthis
functionreturnsforitsinstancesbydefininga__repr__()method.
reversed(seq)¶
Returnareverseiterator.seqmustbeanobjectwhichhas
a__reversed__()methodorsupportsthesequenceprotocol(the
__len__()methodandthe__getitem__()methodwithinteger
argumentsstartingat0).
round(number[,ndigits])¶
Returnnumberroundedtondigitsprecisionafterthedecimal
point.IfndigitsisomittedorisNone,itreturnsthe
nearestintegertoitsinput.
Forthebuilt-intypessupportinground(),valuesareroundedtothe
closestmultipleof10tothepowerminusndigits;iftwomultiplesare
equallyclose,roundingisdonetowardtheevenchoice(so,forexample,
bothround(0.5)andround(-0.5)are0,andround(1.5)is
2).Anyintegervalueisvalidforndigits(positive,zero,or
negative).Thereturnvalueisanintegerifndigitsisomittedor
None.
Otherwise,thereturnvaluehasthesametypeasnumber.
ForageneralPythonobjectnumber,rounddelegatesto
number.__round__.
Note
Thebehaviorofround()forfloatscanbesurprising:forexample,
round(2.675,2)gives2.67insteadoftheexpected2.68.
Thisisnotabug:it’saresultofthefactthatmostdecimalfractions
can’tberepresentedexactlyasafloat.SeeFloatingPointArithmetic:IssuesandLimitationsfor
moreinformation.
classset([iterable])
Returnanewsetobject,optionallywithelementstakenfrom
iterable.setisabuilt-inclass.Seesetand
SetTypes—set,frozensetfordocumentationaboutthisclass.
Forothercontainersseethebuilt-infrozenset,list,
tuple,anddictclasses,aswellasthecollections
module.
setattr(object,name,value)¶
Thisisthecounterpartofgetattr().Theargumentsareanobject,a
string,andanarbitraryvalue.Thestringmaynameanexistingattributeora
newattribute.Thefunctionassignsthevaluetotheattribute,providedthe
objectallowsit.Forexample,setattr(x,'foobar',123)isequivalentto
x.foobar=123.
Note
Sinceprivatenamemanglinghappensat
compilationtime,onemustmanuallymangleaprivateattribute’s
(attributeswithtwoleadingunderscores)nameinordertosetitwith
setattr().
classslice(stop)¶
classslice(start,stop[,step])
Returnasliceobjectrepresentingthesetofindicesspecifiedby
range(start,stop,step).Thestartandstepargumentsdefaultto
None.Sliceobjectshaveread-onlydataattributesstart,
stop,andstepwhichmerelyreturntheargument
values(ortheirdefault).Theyhavenootherexplicitfunctionality;
however,theyareusedbyNumPyandotherthird-partypackages.
Sliceobjectsarealsogeneratedwhenextendedindexingsyntaxisused.For
example:a[start:stop:step]ora[start:stop,i].See
itertools.islice()foranalternateversionthatreturnsaniterator.
sorted(iterable,/,*,key=None,reverse=False)¶
Returnanewsortedlistfromtheitemsiniterable.
Hastwooptionalargumentswhichmustbespecifiedaskeywordarguments.
keyspecifiesafunctionofoneargumentthatisusedtoextractacomparison
keyfromeachelementiniterable(forexample,key=str.lower).The
defaultvalueisNone(comparetheelementsdirectly).
reverseisabooleanvalue.IfsettoTrue,thenthelistelementsare
sortedasifeachcomparisonwerereversed.
Usefunctools.cmp_to_key()toconvertanold-stylecmpfunctiontoa
keyfunction.
Thebuilt-insorted()functionisguaranteedtobestable.Asortis
stableifitguaranteesnottochangetherelativeorderofelementsthat
compareequal—thisishelpfulforsortinginmultiplepasses(for
example,sortbydepartment,thenbysalarygrade).
ThesortalgorithmusesonlyB->C->A->objectandthevalueoftypeisB,
thensuper()searchesC->A->object.
The__mro__attributeoftheobject-or-typeliststhemethod
resolutionsearchorderusedbybothgetattr()andsuper().The
attributeisdynamicandcanchangewhenevertheinheritancehierarchyis
updated.
Ifthesecondargumentisomitted,thesuperobjectreturnedisunbound.If
thesecondargumentisanobject,isinstance(obj,type)mustbetrue.If
thesecondargumentisatype,issubclass(type2,type)mustbetrue(this
isusefulforclassmethods).
Therearetwotypicalusecasesforsuper.Inaclasshierarchywith
singleinheritance,supercanbeusedtorefertoparentclasseswithout
namingthemexplicitly,thusmakingthecodemoremaintainable.Thisuse
closelyparallelstheuseofsuperinotherprogramminglanguages.
Thesecondusecaseistosupportcooperativemultipleinheritanceina
dynamicexecutionenvironment.ThisusecaseisuniquetoPythonandis
notfoundinstaticallycompiledlanguagesorlanguagesthatonlysupport
singleinheritance.Thismakesitpossibletoimplement“diamonddiagrams”
wheremultiplebaseclassesimplementthesamemethod.Gooddesigndictates
thatsuchimplementationshavethesamecallingsignatureineverycase(becausethe
orderofcallsisdeterminedatruntime,becausethatorderadapts
tochangesintheclasshierarchy,andbecausethatordercaninclude
siblingclassesthatareunknownpriortoruntime).
Forbothusecases,atypicalsuperclasscalllookslikethis:
classC(B):
defmethod(self,arg):
super().method(arg)#Thisdoesthesamethingas:
#super(C,self).method(arg)
Inadditiontomethodlookups,super()alsoworksforattribute
lookups.Onepossibleusecaseforthisiscallingdescriptors
inaparentorsiblingclass.
Notethatsuper()isimplementedaspartofthebindingprocessfor
explicitdottedattributelookupssuchassuper().__getitem__(name).
Itdoessobyimplementingitsown__getattribute__()methodforsearching
classesinapredictableorderthatsupportscooperativemultipleinheritance.
Accordingly,super()isundefinedforimplicitlookupsusingstatementsor
operatorssuchassuper()[name].
Alsonotethat,asidefromthezeroargumentform,super()isnot
limitedtouseinsidemethods.Thetwoargumentformspecifiesthe
argumentsexactlyandmakestheappropriatereferences.Thezero
argumentformonlyworksinsideaclassdefinition,asthecompilerfills
inthenecessarydetailstocorrectlyretrievetheclassbeingdefined,
aswellasaccessingthecurrentinstanceforordinarymethods.
Forpracticalsuggestionsonhowtodesigncooperativeclassesusing
super(),seeguidetousingsuper().
classtuple([iterable])
Ratherthanbeingafunction,tupleisactuallyanimmutable
sequencetype,asdocumentedinTuplesandSequenceTypes—list,tuple,range.
classtype(object)¶
classtype(name,bases,dict,**kwds)
Withoneargument,returnthetypeofanobject.Thereturnvalueisa
typeobjectandgenerallythesameobjectasreturnedby
object.__class__.
Theisinstance()built-infunctionisrecommendedfortestingthetype
ofanobject,becauseittakessubclassesintoaccount.
Withthreearguments,returnanewtypeobject.Thisisessentiallya
dynamicformoftheclassstatement.Thenamestringis
theclassnameandbecomesthe__name__attribute.
Thebasestuplecontainsthebaseclassesandbecomesthe
__bases__attribute;ifempty,object,the
ultimatebaseofallclasses,isadded.Thedictdictionarycontains
attributeandmethoddefinitionsfortheclassbody;itmaybecopied
orwrappedbeforebecomingthe__dict__attribute.
Thefollowingtwostatementscreateidenticaltypeobjects:
>>>classX:
...a=1
...
>>>X=type('X',(),dict(a=1))
SeealsoTypeObjects.
Keywordargumentsprovidedtothethreeargumentformarepassedtothe
appropriatemetaclassmachinery(usually__init_subclass__())
inthesamewaythatkeywordsinaclass
definition(besidesmetaclass)would.
SeealsoCustomizingclasscreation.
Changedinversion3.6:Subclassesoftypewhichdon’toverridetype.__new__mayno
longerusetheone-argumentformtogetthetypeofanobject.
vars([object])¶
Returnthe__dict__attributeforamodule,class,instance,
oranyotherobjectwitha__dict__attribute.
Objectssuchasmodulesandinstanceshaveanupdateable__dict__
attribute;however,otherobjectsmayhavewriterestrictionsontheir
__dict__attributes(forexample,classesusea
types.MappingProxyTypetopreventdirectdictionaryupdates).
Withoutanargument,vars()actslikelocals().Note,the
localsdictionaryisonlyusefulforreadssinceupdatestothelocals
dictionaryareignored.
ATypeErrorexceptionisraisedifanobjectisspecifiedbut
itdoesn’thavea__dict__attribute(forexample,if
itsclassdefinesthe__slots__attribute).
zip(*iterables,strict=False)¶
Iterateoverseveraliterablesinparallel,producingtupleswithanitem
fromeachone.
Example:
>>>foriteminzip([1,2,3],['sugar','spice','everythingnice']):
...print(item)
...
(1,'sugar')
(2,'spice')
(3,'everythingnice')
Moreformally:zip()returnsaniteratoroftuples,wherethei-th
tuplecontainsthei-thelementfromeachoftheargumentiterables.
Anotherwaytothinkofzip()isthatitturnsrowsintocolumns,and
columnsintorows.Thisissimilartotransposingamatrix.
zip()islazy:Theelementswon’tbeprocesseduntiltheiterableis
iteratedon,e.g.byaforlooporbywrappingina
list.
Onethingtoconsideristhattheiterablespassedtozip()couldhave
differentlengths;sometimesbydesign,andsometimesbecauseofabugin
thecodethatpreparedtheseiterables.Pythonoffersthreedifferent
approachestodealingwiththisissue:
Bydefault,zip()stopswhentheshortestiterableisexhausted.
Itwillignoretheremainingitemsinthelongeriterables,cuttingoff
theresulttothelengthoftheshortestiterable:
>>>list(zip(range(3),['fee','fi','fo','fum']))
[(0,'fee'),(1,'fi'),(2,'fo')]
zip()isoftenusedincaseswheretheiterablesareassumedtobe
ofequallength.Insuchcases,it’srecommendedtousethestrict=True
option.Itsoutputisthesameasregularzip():
>>>list(zip(('a','b','c'),(1,2,3),strict=True))
[('a',1),('b',2),('c',3)]
Unlikethedefaultbehavior,itchecksthatthelengthsofiterablesare
identical,raisingaValueErroriftheyaren’t:
>>>list(zip(range(3),['fee','fi','fo','fum'],strict=True))
Traceback(mostrecentcalllast):
...
ValueError:zip()argument2islongerthanargument1
Withoutthestrict=Trueargument,anybugthatresultsiniterablesof
differentlengthswillbesilenced,possiblymanifestingasahard-to-find
buginanotherpartoftheprogram.
Shorteriterablescanbepaddedwithaconstantvaluetomakeallthe
iterableshavethesamelength.Thisisdoneby
itertools.zip_longest().
Edgecases:Withasingleiterableargument,zip()returnsan
iteratorof1-tuples.Withnoarguments,itreturnsanemptyiterator.
Tipsandtricks:
Theleft-to-rightevaluationorderoftheiterablesisguaranteed.This
makespossibleanidiomforclusteringadataseriesinton-lengthgroups
usingzip(*[iter(s)]*n,strict=True).Thisrepeatsthesameiterator
ntimessothateachoutputtuplehastheresultofncallstothe
iterator.Thishastheeffectofdividingtheinputinton-lengthchunks.
zip()inconjunctionwiththe*operatorcanbeusedtounzipa
list:
>>>x=[1,2,3]
>>>y=[4,5,6]
>>>list(zip(x,y))
[(1,4),(2,5),(3,6)]
>>>x2,y2=zip(*zip(x,y))
>>>x==list(x2)andy==list(y2)
True
Changedinversion3.10:Addedthestrictargument.
__import__(name,globals=None,locals=None,fromlist=(),level=0)¶
Note
ThisisanadvancedfunctionthatisnotneededineverydayPython
programming,unlikeimportlib.import_module().
Thisfunctionisinvokedbytheimportstatement.Itcanbe
replaced(byimportingthebuiltinsmoduleandassigningto
builtins.__import__)inordertochangesemanticsofthe
importstatement,butdoingsoisstronglydiscouragedasit
isusuallysimplertouseimporthooks(seePEP302)toattainthesame
goalsanddoesnotcauseissueswithcodewhichassumesthedefaultimport
implementationisinuse.Directuseof__import__()isalso
discouragedinfavorofimportlib.import_module().
Thefunctionimportsthemodulename,potentiallyusingthegivenglobals
andlocalstodeterminehowtointerpretthenameinapackagecontext.
Thefromlistgivesthenamesofobjectsorsubmodulesthatshouldbe
importedfromthemodulegivenbyname.Thestandardimplementationdoes
notuseitslocalsargumentatallandusesitsglobalsonlyto
determinethepackagecontextoftheimportstatement.
levelspecifieswhethertouseabsoluteorrelativeimports.0(the
default)meansonlyperformabsoluteimports.Positivevaluesfor
levelindicatethenumberofparentdirectoriestosearchrelativetothe
directoryofthemodulecalling__import__()(seePEP328forthe
details).
Whenthenamevariableisoftheformpackage.module,normally,the
top-levelpackage(thenameuptillthefirstdot)isreturned,notthe
modulenamedbyname.However,whenanon-emptyfromlistargumentis
given,themodulenamedbynameisreturned.
Forexample,thestatementimportspamresultsinbytecoderesemblingthe
followingcode:
spam=__import__('spam',globals(),locals(),[],0)
Thestatementimportspam.hamresultsinthiscall:
spam=__import__('spam.ham',globals(),locals(),[],0)
Notehow__import__()returnsthetoplevelmoduleherebecausethisis
theobjectthatisboundtoanamebytheimportstatement.
Ontheotherhand,thestatementfromspam.hamimporteggs,sausageas
sausresultsin
_temp=__import__('spam.ham',globals(),locals(),['eggs','sausage'],0)
eggs=_temp.eggs
saus=_temp.sausage
Here,thespam.hammoduleisreturnedfrom__import__().Fromthis
object,thenamestoimportareretrievedandassignedtotheirrespective
names.
Ifyousimplywanttoimportamodule(potentiallywithinapackage)byname,
useimportlib.import_module().
Changedinversion3.3:Negativevaluesforlevelarenolongersupported(whichalsochanges
thedefaultvalueto0).
Changedinversion3.9:Whenthecommandlineoptions-Eor-Iarebeingused,
theenvironmentvariablePYTHONCASEOKisnowignored.
Footnotes
1
NotethattheparseronlyacceptstheUnix-styleendoflineconvention.
Ifyouarereadingthecodefromafile,makesuretousenewlineconversion
modetoconvertWindowsorMac-stylenewlines.
Previoustopic
Introduction
Nexttopic
Built-inConstants
ThisPage
ReportaBug
ShowSource
Navigation
index
modules|
next|
previous|
Python»
3.10.4Documentation»
ThePythonStandardLibrary»
Built-inFunctions
|
"