Python Pocket Reference 4th Edition Book

210 Pages • 22,067 Words • PDF • 1.3 MB
Uploaded at 2021-09-24 14:04

This document was submitted by our user and they confirm that they have the consent to share it. Assuming that you are writer or own the copyright of this document, report to us by using this DMCA report button.


Python in Your Pocketÿm

Python! Pocket Reference

m

m

O’REILLY'

Mark Lutz

Programming Languages

O’REILLY Python Pocket Reference This handy book is an easy-to-use reference to the core language, with descriptions of commonly used modules and toolkits, and a guide to recent changes, new features, and upgraded built-ins all updated to cover Python 3.X as well as version 2.6.



— —

widely recognized as the world's leading Python trainer Python Pocket Reference, Fourth Edition, is the perfect companion to his classic Python tutorials, Learning Python and Programming Python (both O’Reilly).

Written by Mark Lutz

This edition covers: Built-in object types, including numbers, lists, dictionaries, and more Statements and syntax for creating and processing objects Functions and modules for structuring and reusing code

Python's object-oriented programming tools The exception-handling model Built-in functions, exceptions, and attributes

Special operator overloading methods Widely used standard library modules and extensions Command-line options and development tools

Python idioms and hints Mark Lutz, a pioneering figure in the Python community since 1992, has written some of the earliest and bestselling texts on Python.

oreilly.com US $14.99

CAN $18.99

ISBN: 978-0-596-15808-8

5 14 9 9 9

7805961 58088

Safari Books Online

Free online edition for 45 days with purchase of this book. Details on last page.

More free ebooks : http://fast-file.blogspot.com

Python 3RFNHW5HIHUHQFH

More free ebooks : http://fast-file.blogspot.com

More free ebooks : http://fast-file.blogspot.com

FOURTH EDITION

Python 3RFNHW5HIHUHQFH

0DUN/XW]

O REILLY Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo

More free ebooks : http://fast-file.blogspot.com

§

Python Pocket Reference, Fourth Edition E\0DUN/XW] &RS\ULJKW‹0DUN/XW]$OOULJKWVUHVHUYHG 3ULQWHGLQ&DQDGD 3XEOLVKHGE\2¦5HLOO\0HGLD,QF*UDYHQVWHLQ+LJKZD\1RUWK6H EDVWRSRO&$ 2¦5HLOO\ERRNVPD\EHSXUFKDVHGIRUHGXFDWLRQDOEXVLQHVVRUVDOHVSURPR WLRQDOXVH2QOLQHHGLWLRQVDUHDOVRDYDLODEOHIRUPRVWWLWOHV KWWSP\VDIDUL ERRNVRQOLQHFRP )RUPRUHLQIRUPDWLRQFRQWDFWRXUFRUSRUDWHLQVWLWXWLRQDO VDOHVGHSDUWPHQW  RUFRUSRUDWH#RUHLOO\FRP

Editor: -XOLH6WHHOH Production Editor: 6XPLWD0XNKHUML Proofreader: .LHO9DQ+RUQ Indexer: -RKQ%LFNHOKDXSW Cover Designer: .DUHQ0RQWJRPHU\ Interior Designer: 'DYLG)XWDWR Printing History: 2FWREHU -DQXDU\ )HEUXDU\ 2FWREHU

)LUVW(GLWLRQ 6HFRQG(GLWLRQ 7KLUG(GLWLRQ )RXUWK(GLWLRQ

1XWVKHOO+DQGERRNWKH1XWVKHOO+DQGERRNORJRDQGWKH2¦5HLOO\ORJRDUH UHJLVWHUHG WUDGHPDUNV RI 2¦5HLOO\ 0HGLD ,QF 7KH 3RFNHW 5HIHUHQFH VHULHV GHVLJQDWLRQV3\WKRQ3RFNHW5HIHUHQFHWKHLPDJHRIDURFNS\WKRQDQGUH ODWHGWUDGHGUHVVDUHWUDGHPDUNVRI2¦5HLOO\0HGLD,QF 0DQ\RIWKHGHVLJQDWLRQVXVHGE\PDQXIDFWXUHUVDQGVHOOHUVWRGLVWLQJXLVK WKHLUSURGXFWVDUHFODLPHGDVWUDGHPDUNV:KHUHWKRVHGHVLJQDWLRQVDSSHDU LQWKLVERRNDQG2¦5HLOO\0HGLD,QFZDVDZDUHRIDWUDGHPDUNFODLPWKH GHVLJQDWLRQVKDYHEHHQSULQWHGLQFDSVRULQLWLDOFDSV :KLOHHYHU\SUHFDXWLRQKDVEHHQWDNHQLQWKHSUHSDUDWLRQRIWKLVERRNWKH SXEOLVKHUDQGDXWKRUDVVXPHQRUHVSRQVLELOLW\IRUHUURUVRURPLVVLRQVRUIRU GDPDJHVUHVXOWLQJIURPWKHXVHRIWKHLQIRUPDWLRQFRQWDLQHGKHUHLQ ,6%1 >70@ 

More free ebooks : http://fast-file.blogspot.com

Contents

Python Pocket Reference Introduction Conventions Command-Line Options Python Options Program Specification Environment Variables Operational Variables Command-Line Option Variables Built-in Types and Operators Operators and Precedence Operator Usage Notes Operations by Category Sequence Operation Notes Specific Built-in Types Numbers Strings Unicode Strings Lists Dictionaries Tuples Files

1 1 2 4 4 6 7 7 8 8 8 10 11 15 16 16 19 33 36 41 44 45 v

More free ebooks : http://fast-file.blogspot.com

Sets Other Common Types Type Conversions Statements and Syntax Syntax Rules Name Rules Specific Statements The Assignment Statement The Expression Statement The print Statement The if Statement The while Statement The for Statement The pass Statement The break Statement The continue Statement The del Statement The def Statement The return Statement The yield Statement The global Statement The nonlocal Statement The import Statement The from Statement The class Statement The try Statement The raise Statement The assert Statement The with Statement Python 2.X Statements Namespace and Scope Rules Qualified Names: Object Namespaces vi | Table of Contents

49 51 52 53 53 54 56 57 59 60 62 62 63 63 63 64 64 64 68 68 70 70 71 72 73 75 78 80 80 82 82 83

More free ebooks : http://fast-file.blogspot.com

Unqualified Names: Lexical Scopes Statically Nested Scopes Object-Oriented Programming Classes and Instances Pseudoprivate Attributes New Style Classes Operator Overloading Methods For All Types For Collections (Sequences, Mappings) For Numbers (Binary Operators) For Numbers (Other Operations) For Descriptors For Context Managers Python 2.X Operator Overloading Methods Built-in Functions Python 2.X Built-in Functions Built-in Exceptions Superclasses (Categories) Specific Exceptions Raised Warning Category Exceptions Warnings Framework Python 2.X Built-in Exceptions Built-in Attributes Standard Library Modules The sys Module The string Module Module Functions and Classes Constants The os System Module Administrative Tools Portability Constants Shell Commands

83 84 85 85 86 87 88 88 93 94 97 98 99 99 102 119 124 124 125 129 130 131 131 132 133 139 139 140 141 141 142 143

Table of Contents | vii

More free ebooks : http://fast-file.blogspot.com

Environment Tools File Descriptor Tools File Pathname Tools Process Control The os.path Module The re Pattern-Matching Module Module Functions Regular Expression Objects Match Objects Pattern Syntax Object Persistence Modules dbm and shelve Modules pickle Module The tkinter GUI Module and Tools tkinter Example tkinter Core Widgets Common Dialog Calls Additional tkinter Classes and Tools Tcl/Tk-to-Python/tkinter Mappings Internet Modules and Tools Commonly Used Library Modules Other Standard Library Modules The math Module The time Module The datetime Module Threading Modules Binary Data Parsing Python Portable SQL Database API API Usage Example Module Interface Connection Objects Cursor Objects viii | Table of Contents

144 145 147 150 153 155 155 157 158 159 163 164 166 168 168 169 170 171 171 173 173 175 176 176 177 177 178 179 179 180 181 181

More free ebooks : http://fast-file.blogspot.com

Type Objects and Constructors Python Idioms and Hints Core Language Hints Environment Hints Usage Hints Assorted Hints Index

182 183 183 184 185 187 189

Table of Contents | ix

More free ebooks : http://fast-file.blogspot.com

More free ebooks : http://fast-file.blogspot.com

Python Pocket Reference

Introduction 3\WKRQLVDJHQHUDOSXUSRVHREMHFWRULHQWHGDQGRSHQVRXUFH FRPSXWHU SURJUDPPLQJ ODQJXDJH ,W LV FRPPRQO\ XVHG IRU ERWKVWDQGDORQHSURJUDPVDQGVFULSWLQJDSSOLFDWLRQVLQDZLGH YDULHW\RIGRPDLQVE\KXQGUHGVRIWKRXVDQGVRIGHYHORSHUV 3\WKRQ LV GHVLJQHG WR RSWLPL]H GHYHORSHU SURGXFWLYLW\ VRIW ZDUHTXDOLW\SURJUDPSRUWDELOLW\DQGFRPSRQHQWLQWHJUDWLRQ 3\WKRQSURJUDPVUXQRQPRVWSODWIRUPVLQFRPPRQXVHLQ FOXGLQJ PDLQIUDPHV DQG VXSHUFRPSXWHUV 8QL[ DQG /LQX[ :LQGRZVDQG0DFLQWRVK-DYDDQG1(7DQGPRUH 7KLV SRFNHW UHIHUHQFH VXPPDUL]HV 3\WKRQ W\SHV DQG VWDWH PHQWV VSHFLDO PHWKRG QDPHV EXLOWLQ IXQFWLRQV DQG H[FHS WLRQV FRPPRQO\ XVHG VWDQGDUG OLEUDU\ PRGXOHV DQG RWKHU SURPLQHQW 3\WKRQ WRROV ,W LV LQWHQGHG WR VHUYH DV D FRQFLVH UHIHUHQFHWRROIRUGHYHORSHUVDQGLVGHVLJQHGWREHDFRPSDQLRQ WRRWKHUERRNVWKDWSURYLGHWXWRULDOVFRGHH[DPSOHVDQGRWKHU OHDUQLQJPDWHULDOV

1

More free ebooks : http://fast-file.blogspot.com

7KLVIRXUWKHGLWLRQFRYHUVERWK3\WKRQYHUVLRQVDQG DQGODWHUUHOHDVHVLQWKH;DQG;OLQHV7KLVHGLWLRQLVIR FXVHGSULPDULO\RQ3\WKRQEXWDOVRGRFXPHQWVGLIIHUHQFHV LQ 3\WKRQ  DQG VR DSSOLHV WR ERWK YHUVLRQV ,W KDV EHHQ WKRURXJKO\ XSGDWHG IRUUHFHQWODQJXDJHDQGOLEUDU\FKDQJHV DQGH[SDQGHGIRUQHZODQJXDJHWRROVDQGWRSLFV 7KLVHGLWLRQDOVRLQFRUSRUDWHVQRWHVDERXWSURPLQHQWHQKDQFH PHQWVLQWKHLPPLQHQW3\WKRQUHOHDVHZKLFKLVLQWHQGHG WRVXEVXPH3\WKRQ LQWKLVERRN3\WKRQJHQHUDOO\UH IHUVWRWKHODQJXDJHYDULDWLRQVLQWURGXFHGE\EXWSUHVHQW LQWKHHQWLUH;OLQH 0XFKRIWKLVHGLWLRQDSSOLHVWRHDUOLHU 3\WKRQUHOHDVHVDVZHOOZLWKWKHH[FHSWLRQRIUHFHQWODQJXDJH H[WHQVLRQV

Conventions 7KHIROORZLQJFRQYHQWLRQVDUHXVHGLQWKLVERRN []

,WHPVLQEUDFNHWVDUHXVXDOO\RSWLRQDO7KHH[FHSWLRQVDUH WKRVHFDVHVZKHUHEUDFNHWVDUHSDUWRI3\WKRQ¦VV\QWD[ *

6RPHWKLQJIROORZHGE\DQDVWHULVNFDQEHUHSHDWHG]HUR RUPRUHWLPHV a|b

,WHPVVHSDUDWHGE\DEDUDUHRIWHQDOWHUQDWLYHV ,WDOLF 8VHGIRUILOHQDPHVDQG85/VDQGWRKLJKOLJKWQHZWHUPV Constant width

8VHG IRU FRGH FRPPDQGV DQG FRPPDQGOLQH RSWLRQV DQGWRLQGLFDWHWKHQDPHVRIPRGXOHVIXQFWLRQVDWWULE XWHVYDULDEOHVDQGPHWKRGV Constant width italic

8VHG IRU UHSODFHDEOH SDUDPHWHU QDPHV LQ FRPPDQG V\QWD[

2 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Using Code Examples 7KLVERRNLVKHUHWRKHOS\RXJHW\RXUMREGRQH,QJHQHUDO\RX PD\ XVH WKH FRGH LQ WKLV ERRN LQ \RXU SURJUDPV DQG GRFX PHQWDWLRQ>> '%s, %s, %.2f' % (42, 'spam', 1 / 3.0) '42, spam, 0.33' >>> '{0}, {1}, {2:.2f}'.format(42, 'spam', 1 / 3.0) '42, spam, 0.33'

$OWKRXJKWKHPHWKRGFDOOVHHPVWREHPRUHDFWLYHO\HYROYLQJ DVWKHVHZRUGVDUHEHLQJZULWWHQWKHH[SUHVVLRQLVXVHGH[WHQ VLYHO\LQH[LVWLQJFRGHDQGERWKIRUPVDUHVWLOOIXOO\VXSSRUWHG 0RUHRYHUDOWKRXJKVRPHYLHZWKHPHWKRGIRUPDVPDUJLQDOO\ PRUHPQHPRQLFDQGFRQVLVWHQWWKHH[SUHVVLRQLVRIWHQVLPSOHU DQGPRUHFRQFLVH$VWKHVHWZRIRUPVDUHODUJHO\MXVWPLQRU YDULDWLRQV RQ D WKHPH RI HTXLYDOHQW IXQFWLRQDOLW\ DQG FRP SOH[LW\WKHUHLVWRGD\QRFRPSHOOLQJUHDVRQWRUHFRPPHQGRQH RYHUWKHRWKHU

String formatting expression 6WULQJIRUPDWWLQJH[SUHVVLRQVUHSODFH%WDUJHWVLQWKHVWULQJRQ WKHOHIWRIWKH %RSHUDWRUZLWKYDOXHVRQWKHULJKW VLPLODUWR &¦Vsprintf ,IPRUHWKDQRQHYDOXHLVWREHUHSODFHGWKH\PXVW EHFRGHGDVDWXSOHWRWKHULJKWRIWKH %RSHUDWRU,IMXVWRQH LWHPLVWREHUHSODFHGLWFDQEHFRGHGDVDVLQJOHYDOXHRURQH LWHPWXSOHRQWKHULJKW QHVWWXSOHVWRIRUPDWDWXSOHLWVHOI ,I NH\QDPHVDUHXVHGRQWKHOHIWDGLFWLRQDU\PXVWEHVXSSOLHG RQWKHULJKWDQG*DOORZVZLGWKDQGSUHFLVLRQWREHSDVVHGLQ G\QDPLFDOO\ 'The knights who say %s!' % 'Ni' 5HVXOW'The knights who say Ni!' "%d %s %d you" % (1, 'spam', 4.0) 5HVXOW'1 spam 4 you' "%(n)d %(x)s" % {"n":1, "x":"spam"} 5HVXOW'1 spam' '%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0) 5HVXOW'0.333333, 0.33, 0.3333'

22 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

,QWKHIRUPDWVWULQJRQWKHOHIWRIWKH %RSHUDWRUVXEVWLWXWLRQ WDUJHWVKDYHWKHIROORZLQJJHQHUDOIRUPDW %[(keyname)][flags][width][.precision]typecode

keynameUHIHUHQFHVDQLWHPLQWKHH[SHFWHGGLFWLRQDU\ flags FDQEH− OHIWMXVWLI\ + QXPHULFVLJQ DVSDFH OHDYHDEODQN EHIRUHSRVLWLYHQXPEHUV DQG 0 ]HURILOO  widthLVWKHWRWDO ILHOG ZLGWK precision JLYHV GLJLWV DIWHU . DQG typecode LV D FKDUDFWHUIURP7DEOH%RWKwidthDQGprecisionFDQEHFRGHG DVD*WRIRUFHWKHLUYDOXHVWREHWDNHQIURPWKHQH[WLWHPLQWKH YDOXHVWRWKHULJKWRIWKH%RSHUDWRUZKHQVL]HVDUHQRWNQRZQ XQWLOUXQWLPH+LQW %sFRQYHUWVDQ\REMHFWWRLWVSULQWUHSUH

VHQWDWLRQVWULQJ 7DEOHVWULQJIRUPDWWLQJW\SHFRGHV Code Meaning

Code Meaning

s

String (or any object, uses str()) X

x with uppercase

r

s, but uses repr(), not str()

e

Floating-point exponent

c

Character (int or str)

E

e with uppercase

d

Decimal (base 10 integer)

f

Floating-point decimal

i

Integer

F

f with uppercase

u

Same as d (obsolete)

g

Floating-point e or f

o

Octal (base 8 integer)

G

Floating-point E or F

x

Hex (base 16 integer)

%

Literal '%'

String formatting method 7KHIRUPDWWLQJPHWKRGFDOOZRUNVVLPLODUWRWKHSULRUVHFWLRQ¦V H[SUHVVLRQEXWLVLQYRNHGZLWKQRUPDOPHWKRGFDOOV\QWD[RQ WKHIRUPDWVWULQJREMHFWDQGLGHQWLILHVVXEVWLWXWLRQWDUJHWVZLWK {}V\QWD[LQVWHDGRI%6XEVWLWXWLRQWDUJHWVLQWKHIRUPDWVWULQJ PD\ QDPH PHWKRGFDOO DUJXPHQWV E\ SRVLWLRQ RU NH\ZRUG QDPH PD\ IXUWKHU UHIHUHQFH DUJXPHQW DWWULEXWHV NH\V DQG RIIVHWVPD\DFFHSWGHIDXOWIRUPDWWLQJRUSURYLGHH[SOLFLWW\SH FRGHVDQGPD\QHVWWDUJHWV\QWD[WRSXOOYDOXHVIURPWKHDU JXPHQWVOLVW Specific Built-in Types | 23

More free ebooks : http://fast-file.blogspot.com

>>> '{0}, {food}'.format(42, food='spam') '42, spam' >>> import sys >>> fmt = '{0.platform} {1[x]} {2[0]}' # attr,key,index >>> fmt.format(sys, {'x': 'ham', 'y': 'eggs'}, 'AB') 'win32 ham A' >>> '{0} {1:+.2f}'.format(1 / 3.0, 1 / 3.0) '0.333333333333 +0.33' >>> '{0:.{1}f}'.format(1 / 3.0, 4) '0.3333'

0RVWRIWKHVHKDYHHTXLYDOHQWVLQ%H[SUHVVLRQXVDJHSDWWHUQV HJ GLFWLRQDU\ NH\ DQG * YDOXH UHIHUHQFHV  WKRXJK WKH H[ SUHVVLRQUHTXLUHVVRPHRSHUDWLRQVWREHFRGHGRXWVLGHWKHIRU PDWVWULQJLWVHOI6XEVWLWXWLRQWDUJHWVLQVWULQJVXVHGIRUIRUPDW PHWKRGFDOOVWDNHWKHIROORZLQJJHQHUDOIRUP {fieldname!conversionflag:formatspec}

,QWKLVVXEVWLWXWLRQWDUJHWV\QWD[ ‡ fieldnameLVDQXPEHURUNH\ZRUGQDPLQJDQDUJXPHQW IROORZHGE\RSWLRQDO£QDPH¤DWWULEXWHRU£>LQGH[@¤FRP SRQHQWUHIHUHQFHV ‡ conversionflagLV£U¤£V¤RU£D¤WRFDOOrepr()str()RU ascii()RQWKHYDOXHUHVSHFWLYHO\ ‡ formatspecVSHFLILHVKRZWKHYDOXHVKRXOGEHSUHVHQWHG LQFOXGLQJGHWDLOVVXFKDVILHOGZLGWKDOLJQPHQWSDGGLQJ GHFLPDOSUHFLVLRQDQGVRRQDQGHQGVZLWKDQRSWLRQDO GDWDW\SHFRGH 7KH formatspec FRPSRQHQW DIWHU WKH FRORQ FKDUDFWHU LV IRU PDOO\ GHVFULEHG DV IROORZV EUDFNHWV LQ WKLV GHQRWH RSWLRQDO FRPSRQHQWVDQGDUHQRWFRGHGOLWHUDOO\  [[fill]align][sign][#][0][width][.precision][typecode]

24 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

alignPD\EH£¤£!¤£ ¤RU£A¤IRUOHIWDOLJQPHQWULJKW

DOLJQPHQWVSDGGLQJDIWHUDVLJQFKDUDFWHURUFHQWHUHGDOLJQ PHQWUHVSHFWLYHO\signPD\EH+−RUVSDFHDQGtypecodeLV JHQHUDOO\WKHVDPHDVWKDWIRU%H[SUHVVLRQVLQ7DEOHZLWKWKH IROORZLQJQRWDEOHH[FHSWLRQV ‡ 7KHiDQGuW\SHFRGHVDUHDEVHQWXVHdWRGLVSOD\LQWHJHUV LQGHFLPDO EDVH IRUPDW ‡ $Q H[WUD b W\SH FRGH GLVSOD\V LQWHJHUV LQ ELQDU\ IRUPDW OLNHXVLQJWKHbin()EXLOWLQ  ‡ $QH[WUD%W\SHFRGHGLVSOD\VDQXPEHUDVDSHUFHQWDJH $VLQJOHREMHFWPD\DOVREHIRUPDWWHGZLWKWKHformat(object formatspec) EXLOWLQ IXQFWLRQ VHH £%XLOWLQ )XQF WLRQV¤RQSDJH )RUPDWWLQJPD\EHFXVWRPL]HGZLWKWKH __format__RSHUDWRURYHUORDGLQJPHWKRGLQFODVVHV VHH£2S HUDWRU2YHUORDGLQJ0HWKRGV¤RQSDJH 

NOTE ,Q 3\WKRQ  DQG ODWHU D £¤ SUHFHGLQJ DQ LQWHJHU RU IORDWLQJSRLQW GHVLJQDWLRQ LQ typecode LQVHUWV WKRXVDQGVVHSDUDWRUFRPPDV '{0:,d}'.format(1000000)

FUHDWHV'1,000,000'DQG '{0:13,.2f}'.format(1000000)

LV' 1,000,000.00' $OVRDVRI3\WKRQILHOGQXPEHUVDUHDXWRPDWLFDOO\ QXPEHUHGVHTXHQWLDOO\LIRPLWWHGIURP fieldname¢WKH IROORZLQJ WKUHH KDYH WKH VDPH HIIHFW WKRXJK DXWRQXPEHUHGILHOGVPD\EHOHVVUHDGDEOHLIPDQ\ILHOGV DUHSUHVHQW '{0}/{1}/{2}'.format(x, y, z)' # explicit num '{}/{}/{}'.format(x, y, z) # 3.1 auto-num '%s/%s/%s' % (x, y, z) # expression

Specific Built-in Types | 25

More free ebooks : http://fast-file.blogspot.com

Template string substitution ,Q3\WKRQDQGODWHUDQRWKHUIRUPRIVLPSOHVWULQJVXEVWL WXWLRQLVSURYLGHGDVDQDOWHUQDWLYHWRWKHVWULQJIRUPDWWLQJH[ SUHVVLRQDQGPHWKRGGHVFULEHGLQWKHSULRUVHFWLRQV7KHXVXDO ZD\RIVXEVWLWXWLQJYDULDEOHVLVZLWKWKH%RSHUDWRU >>> '%(page)i: %(title)s' % {'page':2, 'title': 'PyRef4E'} '2: PyRef4E'

)RUVLPSOHUIRUPDWWLQJWDVNVDTemplateFODVVKDVEHHQDGGHG WRWKHstringPRGXOHWKDWXVHV$WRLQGLFDWHDVXEVWLWXWLRQ >>> >>> >>> '2:

import string t = string.Template('$page: $title') t.substitute({'page':2, 'title': 'PyRef4E'}) PyRef4E'

6XEVWLWXWLRQYDOXHVFDQEHSURYLGHGDVNH\ZRUGDUJXPHQWVRU GLFWLRQDU\NH\V >>> s = string.Template('$who likes $what') >>> s.substitute(who='bob', what=3.14) 'bob likes 3.14' >>> s.substitute(dict(who='bob', what='pie')) 'bob likes pie'

$ safe_substitute PHWKRG LJQRUHV PLVVLQJ NH\V UDWKHU WKDQ UDLVLQJDQH[FHSWLRQ >>> t = string.Template('$page: $title') >>> t.safe_substitute({'page':3}) '3: $title'

String methods ,Q DGGLWLRQ WR WKH format() PHWKRG GHVFULEHG HDUOLHU VWULQJ PHWKRGFDOOVSURYLGHKLJKHUOHYHOWH[WSURFHVVLQJWRROVEH\RQG VWULQJH[SUHVVLRQV7DEOHOLVWVDYDLODEOHVWULQJPHWKRGFDOOV SLVDQ\VWULQJREMHFWLQWKLVWDEOH6WULQJPHWKRGVWKDWPRGLI\ WH[WDOZD\VUHWXUQDQHZVWULQJDQGQHYHUPRGLI\WKHREMHFWLQ SODFH VWULQJVDUHLPPXWDEOH 6HHDOVRWKH rePRGXOHLQWKH VHFWLRQ £7KH UH 3DWWHUQ0DWFKLQJ 0RGXOH¤ RQ SDJH  IRU SDWWHUQEDVHGHTXLYDOHQWVWRVRPHVWULQJW\SHPHWKRGV

26 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

7DEOH3\WKRQVWULQJPHWKRGFDOOV S.capitalize() S.center(width, [, fill]) S.count(sub [, start [, end]]) S.encode([encoding [,errors]]) S.endswith(suffix [, start [, end]]) S.expandtabs([tabsize]) S.find(sub [, start [, end]]) S.format(fmtstr, *args, **kwargs) S.index(sub [, start [, end]]) S.isalnum() S.isalpha() S.isdecimal() S.isdigit() S.isidentifier() S.islower() S.isnumeric() S.isprintable() S.isspace() S.istitle( S.isupper() S.join(iterable) S.ljust(width [, fill]) S.lower() S.lstrip([chars]) S.maketrans(x[, y[, z]]) S.partition(sep) S.replace(old, new [, count]) S.rfind(sub [,start [,end]]) S.rindex(sub [, start [, end]])

Specific Built-in Types | 27

More free ebooks : http://fast-file.blogspot.com

S.rjust(width [, fill]) S.rpartition(sep) S.rsplit([sep[, maxsplit]]) S.rstrip([chars]) S.split([sep [,maxsplit]]) S.splitlines([keepends]) S.startswith(prefix [, start [, end]]) S.strip([chars]) S.swapcase() S.title() S.translate(map) S.upper() S.zfill(width)

byte and bytearray methods 3\WKRQ  bytes DQG bytearray VWULQJ W\SHV KDYH VLPLODU PHWKRGVHWVEXWGRQRWRYHUODSH[DFWO\ZLWKWKHQRUPDO str VWULQJW\SH strLV8QLFRGHWH[WbytesLVUDZELQDU\GDWDDQG bytearrayLVPXWDEOH ,QWKHIROORZLQJset(X) – set(Y)FRP SXWHVLWHPVLQXWKDWDUHQRWLQY ‡ bytes DQG bytearray GR QRW VXSSRUW 8QLFRGH HQFRGLQJ WKH\DUHUDZE\WHVQRWGHFRGHGWH[W RUVWULQJIRUPDWWLQJ str.format DQG WKH % RSHUDWRU LPSOHPHQWHG ZLWK __mod__ ‡ str GRHV QRW VXSSRUW 8QLFRGH GHFRGLQJ LW LV DOUHDG\ GHFRGHGWH[W ‡ bytearrayKDVXQLTXHPXWDEOHLQSODFHPHWKRGVVLPLODUWR OLVW >>> set(dir(str)) - set(dir(bytes)) {'isprintable', 'format', '__mod__', 'encode', 'isidentifier', '_formatter_field_name_split', 'isnumeric', '__rmod__', 'isdecimal', '_formatter_parser', 'maketrans'}

28 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

>>> set(dir(bytes)) - set(dir(str)) {'decode', 'fromhex'} >>> set(dir(bytearray)) - set(dir(bytes)) {'insert', '__alloc__', 'reverse', 'extend', '__delitem__', 'pop', '__setitem__', '__iadd__', 'remove', 'append', '__imul__'}

%HVLGHVPHWKRGV bytesDQG bytearrayDOVRVXSSRUWWKHXVXDO VHTXHQFHRSHUDWLRQVLQ7DEOHRQSDJHDQGbytearrayVXS SRUWVPXWDEOHVHTXHQFHRSHUDWLRQVLQ7DEOHRQSDJH6HH PRUH LQ £8QLFRGH 6WULQJV¤ RQ SDJH  DQG £%XLOWLQ )XQF WLRQV¤RQSDJH

NOTE 7KHVHWRIVWULQJPHWKRGVDYDLODEOHLQ3\WKRQYDULHV VOLJKWO\ HJWKHUHLVDdecodePHWKRGIRU¦VGLIIHUHQW 8QLFRGH W\SH PRGHO  7KH 3\WKRQ  unicode VWULQJ W\SHKDVDQHDUO\LGHQWLFDOLQWHUIDFHWR strREMHFWV &RQVXOW WKH 3\WKRQ  /LEUDU\ 5HIHUHQFH RU UXQ dir(str) DQG help(str.method) LQWHUDFWLYHO\ IRU PRUH GHWDLOV

7KH IROORZLQJ VHFWLRQV JR LQWR PRUH GHWDLO RQ VRPH RI WKH PHWKRGVOLVWHGLQ7DEOH,QDOORIWKHIROORZLQJWKDWUHWXUQD VWULQJUHVXOWWKHUHVXOWLVDQHZVWULQJ %HFDXVHVWULQJVDUHLP PXWDEOHWKH\DUHQHYHUPRGLILHGLQSODFH :KLWHVSDFHPHDQV VSDFHV WDEV DQG HQGRIOLQH FKDUDFWHUV HYHU\WKLQJ LQ string.whitespace 

Searching s.find(sub, [, start [, end]])

5HWXUQV RIIVHW RI WKH ILUVW RFFXUUHQFH RI VWULQJ sub LQ s EHWZHHQ RIIVHWV start DQG end ZKLFK GHIDXOW WR 0 DQG len(s)WKHHQWLUHVWULQJ 5HWXUQV−1LIQRWIRXQG$OVRVHH WKH inPHPEHUVKLSRSHUDWRUZKLFKPD\EHXVHGWRWHVW VXEVWULQJPHPEHUVKLSLQDVWULQJ Specific Built-in Types | 29

More free ebooks : http://fast-file.blogspot.com

s.rfind(sub, [, start [, end]]) /LNHfindEXWVFDQVIURPWKHHQG ULJKWWROHIW  s.index(sub [, start [, end]]) /LNH find EXW UDLVHV ValueError LI QRW IRXQG LQVWHDG RI UHWXUQLQJ−1 s.rindex(sub [, start [, end]]) /LNH rfindEXWUDLVHV ValueErrorLIQRWIRXQGLQVWHDGRI UHWXUQLQJ−1 s.count(sub [, start [, end]])

&RXQWV WKH QXPEHU RI QRQRYHUODSSLQJ RFFXUUHQFHV RIsubLQsIURPRIIVHWVstartWRend GHIDXOWV0len(s)  s.startswith(sub [, start [, end]]) TrueLIVWULQJsVWDUWVZLWKVXEVWULQJsubstartDQGendJLYH RSWLRQDOEHJLQDQGHQGSRLQWVIRUPDWFKLQJsub s.endswith(sub [, start [, end]]) TrueLIVWULQJsHQGVZLWKVXEVWULQJsubstartDQGendJLYH RSWLRQDOEHJLQDQGHQGSRLQWVIRUPDWFKLQJsub

Splitting and joining s.split([sep [, maxsplit]])

5HWXUQVDOLVWRIWKHZRUGVLQWKHVWULQJsXVLQJsepDVWKH GHOLPLWHU VWULQJ ,I maxsplit LV JLYHQ DW PRVW maxsplit VSOLWVDUHGRQH,IsepLVQRWVSHFLILHGRULVNoneDQ\ZKLWH VSDFH VWULQJ LV D VHSDUDWRU 'a*b'.split('*') \LHOGV ['a','b']8VHlist(s)WRFRQYHUWDVWULQJWRDOLVWRIFKDU DFWHUV HJ['a','*','b']  sep.join(iterable)

&RQFDWHQDWHVDQLWHUDEOH HJOLVWRUWXSOH RIVWULQJVLQWR DVLQJOHVWULQJZLWKsepDGGHGEHWZHHQHDFKLWHPsepFDQ EH " DQHPSW\VWULQJ WRFRQYHUWDOLVWRIFKDUDFWHUVWRD VWULQJ '*'.join(['a','b'])\LHOGV'a*b'  s.replace(old, new [, count]) 5HWXUQVDFRS\RIVWULQJsZLWKDOORFFXUUHQFHVRIVXEVWULQJ oldUHSODFHGE\new,IcountLVSDVVHGWKHILUVWcountRF

FXUUHQFHVDUHUHSODFHG7KLVZRUNVOLNHDFRPELQDWLRQRI x=s.split(old)DQGnew.join(x) 30 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

s.splitlines([keepends]) 6SOLWVVWULQJsRQOLQHEUHDNVUHWXUQLQJOLQHVOLVW7KHUHVXOW GRHV QRW UHWDLQ OLQH EUHDN FKDUDFWHUV XQOHVV keepends LV

WUXH

Formatting s.capitalize()

&DSLWDOL]HVWKHILUVWFKDUDFWHURIVWULQJs s.expandtabs([tabsize])

5HSODFHVWDEVLQVWULQJsZLWKtabsizeVSDFHV GHIDXOWLV  s.strip([chars])

5HPRYHVOHDGLQJDQGWUDLOLQJZKLWHVSDFHIURPVWULQJs RU FKDUDFWHUVLQcharsLISDVVHG  s.lstrip([chars])

5HPRYHVOHDGLQJZKLWHVSDFHIURPVWULQJs RUFKDUDFWHUV LQcharsLISDVVHG  s.rstrip([chars])

5HPRYHVWUDLOLQJZKLWHVSDFHIURPVWULQJ s RUFKDUDFWHUV LQcharsLISDVVHG  s.swapcase()

&RQYHUWVDOOORZHUFDVHOHWWHUVWRXSSHUFDVHDQGYLFHYHUVD s.upper()

&RQYHUWVDOOOHWWHUVWRXSSHUFDVH s.lower()

&RQYHUWVDOOOHWWHUVWRORZHUFDVH s.ljust(width [, fill]) /HIWMXVWLILHVVWULQJsLQDILHOGRIWKHJLYHQwidthSDGVRQ ULJKWZLWKFKDUDFWHUfill ZKLFKGHIDXOWVWRDVSDFH 7KH

6WULQJIRUPDWWLQJH[SUHVVLRQDQGPHWKRGFDQDFKLHYHVLP LODUHIIHFWV s.rjust(width [, fill])

5LJKWMXVWLILHVVWULQJ sLQDILHOGRIWKHJLYHQ widthSDGV RQOHIWZLWKFKDUDFWHUfill ZKLFKGHIDXOWVWRDVSDFH 7KH 6WULQJIRUPDWWLQJH[SUHVVLRQDQGPHWKRGFDQDFKLHYHVLP LODUHIIHFWV Specific Built-in Types | 31

More free ebooks : http://fast-file.blogspot.com

s.center(width [, fill]) &HQWHUVVWULQJsLQDILHOGRIWKHJLYHQwidthSDGVRQOHIW DQGULJKWZLWKFKDUDFWHUfill ZKLFKGHIDXOWVWRDVSDFH 

7KH6WULQJIRUPDWWLQJH[SUHVVLRQDQGPHWKRGFDQDFKLHYH VLPLODUHIIHFWV s.zfill(width)

3DGVVWULQJ sRQOHIWZLWK]HURGLJLWVWRSURGXFHDVWULQJ UHVXOWRIWKHGHVLUHGwidth FDQDOVRDFKLHYHZLWK%VWULQJ IRUPDWWLQJH[SUHVVLRQ  s.translate(table [, deletechars])

'HOHWHV DOO FKDUDFWHUV IURP VWULQJ s WKDW DUH LQ deletechars LISUHVHQW WKHQWUDQVODWHVWKHFKDUDFWHUVXV LQJtableDFKDUDFWHUVWULQJJLYLQJWKHWUDQVODWLRQIRU HDFKFKDUDFWHUYDOXHLQGH[HGE\LWVRUGLQDO s.title()

5HWXUQVDWLWOHFDVHGYHUVLRQRIWKHVWULQJZRUGVVWDUWZLWK XSSHUFDVHFKDUDFWHUVDOOUHPDLQLQJFDVHGFKDUDFWHUVDUH ORZHUFDVH

Content tests s.is*()

7KH is*() %RROHDQ WHVWV ZRUN RQ VWULQJV RI DQ\ OHQJWK 7KH\WHVWWKHFRQWHQWRIVWULQJVIRUYDULRXVFDWHJRULHV DQG DOZD\VUHWXUQFalseIRUDQHPSW\ 

The original string module 6WDUWLQJLQ3\WKRQPRVWRIWKHVWULQJSURFHVVLQJIXQFWLRQV SUHYLRXVO\ DYDLODEOH LQ WKH VWDQGDUG string PRGXOH EHFDPH DYDLODEOHDVPHWKRGVRIVWULQJREMHFWV,I XUHIHUHQFHVDVWULQJ REMHFWDstringPRGXOHIXQFWLRQFDOOVXFKDV import string res = string.replace(X, 'span', 'spam')

LVXVXDOO\HTXLYDOHQWLQ3\WKRQWRDVWULQJPHWKRGFDOOVXFK DV res = X.replace('span', 'spam')

32 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

%XWWKHVWULQJPHWKRGFDOOIRUPLVSUHIHUUHGDQGTXLFNHUDQG VWULQJ PHWKRGV UHTXLUH QR PRGXOH LPSRUWV 1RWH WKDW WKH string.join(list, delim)RSHUDWLRQEHFRPHVDPHWKRGRIWKH GHOLPLWHUVWULQJ delim.join(list)$OOWKHVHIXQFWLRQVDUHUH PRYHGIURPWKHstringPRGXOHLQ3\WKRQXVHWKHHTXLYD OHQWVWULQJREMHFWPHWKRGVLQVWHDG

Unicode Strings 7HFKQLFDOO\DOOWH[WLV8QLFRGHWH[WLQFOXGLQJWKHVLPSOHELW $6&,, HQFRGLQJ VFKHPH 3\WKRQ VXSSRUWV 8QLFRGH ZLGH FKDUDFWHUVWULQJVZKLFKUHSUHVHQWHDFKFKDUDFWHUZLWKRU PRUHELWVQRW7KLVVXSSRUWGLIIHUVLQ3\WKRQOLQHV3\WKRQ WUHDWVDOOWH[WDV8QLFRGHDQGUHSUHVHQWVELQDU\GDWDVHSD UDWHO\ ZKLOH 3\WKRQ ; GLVWLQJXLVKHV ELW WH[W DQG GDWD IURPZLGHU8QLFRGHWH[W6SHFLILFDOO\ ‡ ,Q3\WKRQWKHstrW\SHUHSUHVHQWVERWKELWWH[WDQG ELQDU\ GDWD DQG D VHSDUDWH unicode W\SH KDQGOHV ZLGH FKDUDFWHU 8QLFRGH WH[W $ u'ccc' OLWHUDO IRUP VXSSRUWV FRGLQJELQDU\GDWDDQGDcodecsPRGXOHVXSSRUWVUHDGLQJ DQGZULWLQJILOHVFRQWDLQLQJ8QLFRGHWH[W ‡ ,Q3\WKRQWKHQRUPDOstrVWULQJW\SHDQGOLWHUDOKDQ GOHVDOOWH[W ERWKELWDQGZLGHU8QLFRGH DQGDVHSDUDWH bytes W\SH UHSUHVHQWV ELW ELQDU\ GDWD bytes PD\ EH FRGHG ZLWK WKH b'ccc' OLWHUDO IRUP LW LV DQ LPPXWDEOH VHTXHQFHRIVPDOOLQWHJHUVEXWVXSSRUWVPRVWstrRSHUD WLRQVDQGSULQWVDV$6&,,WH[WZKHQSRVVLEOH$OVRLQ ILOHVLPSO\strDQGbytesREMHFWVLQWH[WDQGELQDU\PRGH WH[WPRGHILOHVDXWRPDWLFDOO\HQFRGHDQGGHFRGHWH[WDQG DQ DGGLWLRQDO bytearray W\SH LV D PXWDEOH YDULDQW RI bytesZLWKH[WUDOLVWOLNHPHWKRGVIRULQSODFHFKDQJHV bytearrayLVDOVRSUHVHQWLQEXW bytesLVQRW b'ccc' FUHDWHVDstrLQIRUFRPSDWLELOLW\ 

Specific Built-in Types | 33

More free ebooks : http://fast-file.blogspot.com

Unicode support in Python 3.0 3\WKRQDOORZVQRQ$6&,,FKDUDFWHUVWREHFRGHGLQVWULQJV ZLWKKH[ \x DQGERWKDQGELW8QLFRGH \u\U HVFDSHV ,QDGGLWLRQchr()VXSSRUWV8QLFRGHFKDUDFWHUFRGHV >>> 'A\xE4B' 'AäB' >>> 'A\u00E4B' 'AäB' >>> 'A\U000000E4B' 'AäB' >>> chr(0xe4) 'ä'

1RUPDOVWULQJVPD\EHHQFRGHGLQWRUDZE\WHVDQGUDZE\WHV PD\ EH GHFRGHG LQWR QRUPDO VWULQJV XVLQJ HLWKHU GHIDXOW RU H[SOLFLWHQFRGLQJV >>> 'A\xE4B'.encode('latin-1') b'A\xe4B' >>> 'A\xE4B'.encode() b'A\xc3\xa4B' >>> 'A\xE4B'.encode('utf-8') b'A\xc3\xa4B' >>> >>> b'A\xC3\xA4B'.decode('utf-8') 'AäB'

)LOHREMHFWVDOVRDXWRPDWLFDOO\GHFRGHDQGHQFRGHRQLQSXWDQG RXWSXWDQGDFFHSWDQHQFRGLQJQDPHWRRYHUULGHWKHGHIDXOW HQFRGLQJ >>> S = 'A\xE4B' >>> open('uni.txt', 'w', encoding='utf-8').write(S) 3 >>> open('uni.txt', 'rb').read() b'A\xc3\xa4B' >>> >>> open('uni.txt', 'r', encoding='utf-8').read() 'AäB'

byte and bytearray strings 3\WKRQbytesDQGbytearrayVWULQJREMHFWVUHSUHVHQWELW ELQDU\GDWD LQFOXGLQJHQFRGHG8QLFRGHWH[W SULQWLQ$6&,, 34 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

ZKHQSRVVLEOHDQGVXSSRUWPRVWQRUPDOstrVWULQJRSHUDWLRQV LQFOXGLQJPHWKRGVDQGVHTXHQFHRSHUDWLRQV >>> B = b'spam' >>> B b'spam' >>> B[0] 115 >>> B + b'abc' b'spamabc' >>> B.split(b'a') [b'sp', b'm'] >>> list(B) [115, 112, 97, 109]

# sequence ops

# methods # sequence of int

bytearrayDGGLWLRQDOO\VXSSRUWVOLVWOLNHPXWDEOHRSHUDWLRQV >>> BA = bytearray(b'spam') >>> BA bytearray(b'spam') >>> BA[0] 115 >>> BA + b'abc' bytearray(b'spamabc') >>> BA[0] = 116 # mutability >>> BA.append(115) # list methods >>> BA bytearray(b'tpams')

6HH DOVR WKH GLVFXVVLRQ RI byte DQG bytearray PHWKRGV LQ £6WULQJPHWKRGV¤RQSDJHDQGWKHW\SHFRQVWUXFWRUFDOOVLQ £%XLOWLQ)XQFWLRQV¤RQSDJH3\WKRQKDV bytearray EXWQRWbytes LQb'ccc'LVDV\QRQ\PIRU'ccc'DQGFUHDWHV DQRUPDOstrVWULQJ 

Unicode support in Python 2.X ,Q3\WKRQ;8QLFRGHVWULQJVDUHZULWWHQDVu'string' LQ3\ WKRQWKHQRUPDOVWULQJW\SHDQGOLWHUDODUHXVHGIRU8QL FRGH  $UELWUDU\ 8QLFRGH FKDUDFWHUV FDQ EH ZULWWHQ XVLQJ D VSHFLDOHVFDSHVHTXHQFH\uHHHHZKHUHHHHHLVDIRXUGLJLWKH[ DGHFLPDOQXPEHUIURP 0000WR FFFF7KHWUDGLWLRQDO \xHHHV FDSHVHTXHQFHFDQDOVREHXVHGDQGRFWDOHVFDSHVFDQEHXVHG IRUFKDUDFWHUVXSWR+01FFZKLFKLVUHSUHVHQWHGE\\777

Specific Built-in Types | 35

More free ebooks : http://fast-file.blogspot.com

/LNHQRUPDOVWULQJVDOOLPPXWDEOHVHTXHQFHRSHUDWLRQVDSSO\ WR unicode1RUPDODQG8QLFRGHVWULQJREMHFWVFDQEHIUHHO\ PL[HGLQ3\WKRQFRPELQLQJELWDQG8QLFRGHVWULQJVDO ZD\V FRHUFHV WR 8QLFRGH XVLQJ WKH GHIDXOW $6&,, HQFRGLQJ HJWKHUHVXOWRI 'a' + u'bc'LV u'abc' 0L[HGW\SHRSHUD WLRQV DVVXPH WKH ELW VWULQJ FRQWDLQV ELW 86 $6&,, GDWD DQG UDLVH DQ HUURU IRU QRQ$6&,, FKDUDFWHUV  7KH EXLOWLQ str()DQGunicode()IXQFWLRQVFDQEHXVHGWRFRQYHUWEHWZHHQ QRUPDODQG8QLFRGHVWULQJV7KHencodeVWULQJPHWKRGDSSOLHV DGHVLUHGHQFRGLQJVFKHPHWR8QLFRGHVWULQJV$KDQGIXORI UHODWHGPRGXOHV HJ codecs DQGEXLOWLQIXQFWLRQVDUHDOVR DYDLODEOH

Lists /LVWVDUHPXWDEOH FKDQJHDEOH DUUD\VRIREMHFWUHIHUHQFHVDF FHVVHGE\RIIVHW

Literals and creation /LVWVDUHZULWWHQDVDFRPPDVHSDUDWHGVHULHVRIYDOXHVHQFORVHG LQVTXDUHEUDFNHWV []

$QHPSW\OLVW [0, 1, 2, 3]

$IRXULWHPOLVWLQGH[HV alist = ['spam', [42, 3.1415], 1.23, {}] 1HVWHGVXEOLVWValist[1][0]IHWFKHV alist = list('spam')

&UHDWHVDOLVWRIDOOLWHPVLQDQ\LWHUDEOHE\FDOOLQJWKHW\SH FRQVWUXFWRUIXQFWLRQ alist = [x**2 for x in range(9)]

&UHDWHVDOLVWE\FROOHFWLQJH[SUHVVLRQUHVXOWVGXULQJLWHU DWLRQ OLVWFRPSUHKHQVLRQ 

36 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Operations 2SHUDWLRQV LQFOXGH DOO VHTXHQFH RSHUDWLRQV VHH 7DEOH  RQ SDJH SOXVDOOPXWDEOHVHTXHQFHRSHUDWLRQV VHH7DEOHRQ SDJH SOXVWKHIROORZLQJOLVWPHWKRGV alist.append(x)

,QVHUWVWKHVLQJOHREMHFWxDWWKHHQGRIalistFKDQJLQJWKH OLVWLQSODFH alist.extend(x)

,QVHUWVHDFKLWHPLQDQ\LWHUDEOH xDWWKHHQGRI alistLQ SODFH DQ LQSODFH +  6LPLODU WR alist[len(alist):] = list(x) alist.sort(key=None, reverse=False) 6RUWV alist LQSODFH LQ DVFHQGLQJ RUGHU E\ GHIDXOW ,I SDVVHG keyVSHFLILHVDIXQFWLRQRIRQHDUJXPHQWWKDWLV

XVHGWRH[WUDFWRUFRPSXWHDFRPSDULVRQYDOXHIURPHDFK OLVWHOHPHQW,IreverseLVSDVVHGDQGtrueWKHOLVWHOHPHQWV DUHVRUWHGDVLIHDFKFRPSDULVRQZHUHUHYHUVHG)RUH[ DPSOH alist.sort(key=str.lower, reverse=True) 6HH DOVRWKHsorted()EXLOWLQIXQFWLRQ alist.reverse()

5HYHUVHVLWHPVLQalistLQSODFH alist.index(x [, i [, j]])

5HWXUQV WKH LQGH[ RI WKH ILUVW RFFXUUHQFH RI REMHFW x LQ alistUDLVHVDQH[FHSWLRQLIQRWIRXQG7KLVLVDVHDUFK PHWKRG,IiDQGjDUHSDVVHGLWUHWXUQVWKHVPDOOHVWkVXFK WKDWs[k] == xDQGi >> [ord(x) for x in 'spam'] [115, 112, 97, 109] >>> map(ord, 'spam') [115, 112, 97, 109]

38 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

EXWFDQRIWHQDYRLGFUHDWLQJDWHPSRUDU\KHOSHUIXQFWLRQ >>> [0, >>> [0,

[x**2 for x in range(5)] 1, 4, 9, 16] map((lambda x: x**2), range(5)) 1, 4, 9, 16]

&RPSUHKHQVLRQVZLWKFRQGLWLRQVDUHVLPLODUWRfilter >>> [0, >>> [0,

[x for x in range(5) if x % 2 == 0] 2, 4] filter((lambda x: x % 2 == 0), range(5)) 2, 4]

&RPSUHKHQVLRQVZLWKQHVWHGforORRSVDUHVLPLODUWRWKHQRU PDOfor >>> [y for x in range(3) for y in range(3)] [0, 1, 2, 0, 1, 2, 0, 1, 2] >>> >>> ... ... >>> [0,

res = [] for x in range(3): for y in range(3): res.append(y) res 1, 2, 0, 1, 2, 0, 1, 2]

Generator expressions $VRI3\WKRQJHQHUDWRUH[SUHVVLRQVDFKLHYHUHVXOWVVLPLODU WROLVWFRPSUHKHQVLRQVZLWKRXWJHQHUDWLQJDSK\VLFDOOLVWWR KROGDOOUHVXOWV*HQHUDWRUH[SUHVVLRQVGHILQHDVHWRIUHVXOWV EXWGRQRWPDWHULDOL]HWKHHQWLUHOLVWWRVDYHPHPRU\LQVWHDG WKH\FUHDWHDJHQHUDWRUWKDWZLOOUHWXUQHOHPHQWVRQHE\RQHLQ LWHUDWLRQFRQWH[WV)RUH[DPSOH ords = (ord(x) for x in aString if x not in skipThese) for o in ords: ...

*HQHUDWRU H[SUHVVLRQV DUH ZULWWHQ LQVLGH SDUHQWKHVHV UDWKHU WKDQVTXDUHEUDFNHWVEXWRWKHUZLVHVXSSRUWDOOOLVWFRPSUH KHQVLRQ V\QWD[ 7KH SDUHQWKHVHV XVHG IRU D IXQFWLRQ ZLWK D VLQJOHDUJXPHQWVXIILFHZKHQFUHDWLQJDQLWHUDWRUWREHSDVVHG WRDIXQFWLRQ sum(ord(x) for x in aString)

Specific Built-in Types | 39

More free ebooks : http://fast-file.blogspot.com

*HQHUDWRUH[SUHVVLRQORRSYDULDEOHV xLQWKHSULRUH[DPSOH DUHQRWDFFHVVLEOHRXWVLGHWKHJHQHUDWRUH[SUHVVLRQ,Q3\WKRQ ;OLVWFRPSUHKHQVLRQVOHDYHWKHYDULDEOHDVVLJQHGWRLWVODVW YDOXH3\WKRQFKDQJHVWKLVWRPDNHOLVWFRPSUHKHQVLRQV¦ VFRSHZRUNOLNHJHQHUDWRUH[SUHVVLRQV 8VHWKHLWHUDWRUSURWRFRO¦V __next__()PHWKRG next()LQ3\ WKRQ ;  WR VWHS WKURXJK UHVXOWV RXWVLGH LWHUDWLRQ FRQWH[WV VXFKDVforORRSVDQGXVHWKH listFDOOWRSURGXFHDOLVWRIDOO UHVXOWVLIUHTXLUHG >>> squares = (x ** 2 for x in range(5)) >>> squares >>> squares.__next__() 0 >>> squares.__next__() # or next(squares) 1 >>> list(x ** 2 for x in range(5)) [0, 1, 4, 9, 16]

6HH£7KH\LHOG6WDWHPHQW¤RQSDJHIRUPRUHRQJHQHUDWRUV DQGLWHUDWRUVLQFOXGLQJDGGLWLRQDOJHQHUDWRUPHWKRGV

Other generators and comprehensions 6HH DOVR WKH UHODWHG yield VWDWHPHQW GLFWLRQDU\ FRPSUHKHQ VLRQVDQGVHWFRPSUHKHQVLRQVHOVHZKHUHLQWKLVERRN7KHODW WHUWZRDUHVLPLODUH[SUHVVLRQVWKDWSURGXFHGLFWLRQDULHVDQG VHWVWKH\VXSSRUWV\QWD[LGHQWLFDOWROLVWFRPSUHKHQVLRQVDQG JHQHUDWRUH[SUHVVLRQVEXWDUHFRGHGZLWKLQ{}DQGGLFWLRQDU\ FRPSUHKHQVLRQVEHJLQZLWKDkey:valueH[SUHVVLRQSDLU >>> [x * x for x in range(10)] # List comp. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> (x * x for x in range(10))

# Generator expr.

>>> {x * x for x in range(10)} # Set comp. (3.0) {0, 1, 4, 81, 64, 9, 16, 49, 25, 36} >>> {x: x * x for x in range(10)} # Dict comp. (3.0) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

40 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Dictionaries 'LFWLRQDULHVDUHPXWDEOHWDEOHVRIREMHFWUHIHUHQFHVDFFHVVHG E\ NH\ QRW SRVLWLRQ 7KH\ DUH XQRUGHUHG FROOHFWLRQV LPSOHPHQWHG LQWHUQDOO\ DV G\QDPLFDOO\ H[SDQGDEOH KDVK WD EOHV'LFWLRQDULHVKDYHFKDQJHGVLJQLILFDQWO\LQ3\WKRQ ‡ ,Q 3\WKRQ ; WKH keys()values()items() PHWKRGV UHWXUQOLVWVWKHUHLVDhas_key()ORRNXSPHWKRGWKHUHDUH GLVWLQFW LWHUDWRU PHWKRGV iterkeys()itervalues() iteritems()DQGGLFWLRQDULHVPD\EHFRPSDUHGGLUHFWO\ ‡ ,Q3\WKRQWKH keys()values()items()PHWKRGVUH WXUQLWHUDEOHYLHZREMHFWVLQVWHDGRIOLVWVhas_key()LVUH PRYHG LQ IDYRU RI in H[SUHVVLRQV 3\WKRQ ; LWHUDWRU PHWKRGV DUH UHPRYHG LQ IDYRU RI YLHZ REMHFW LWHUDWLRQ GLFWLRQDULHV FDQQRW EH FRPSDUHG GLUHFWO\ EXW WKHLU sorted(D.items())FDQDQGWKHUHLVDQHZGLFWLRQDU\FRP SUHKHQVLRQH[SUHVVLRQ ‡ 3\WKRQYLHZREMHFWVSURGXFHUHVXOWVRQGHPDQGUHWDLQ WKHRULJLQDORUGHULQWKHGLFWLRQDU\UHIOHFWIXWXUHGLFWLRQ DU\FKDQJHVDQGPD\VXSSRUWVHWRSHUDWLRQV.H\YLHZV DUHDOZD\VVHWOLNHYDOXHYLHZVQHYHUDUHDQGLWHPYLHZV DUHLIDOOWKHLULWHPVDUHXQLTXHDQGKDVKDEOH LPPXWDEOH  6HH £6HWV¤ RQ SDJH  IRU VHW H[SUHVVLRQV WKDW PD\ EH DSSOLHG WR VRPH YLHZV 3DVV YLHZV WR WKH list() FDOO WR IRUFHJHQHUDWLRQRIDOOWKHLUUHVXOWVDWRQFH HJIRUGLV SOD\RUIRUlist.sort() 

Literals and creation 'LFWLRQDU\ OLWHUDOV DUH ZULWWHQ DV FRPPDVHSDUDWHG VHULHV RI key:valueSDLUVLQVLGHFXUO\EUDFHVWKHdict()EXLOWLQVXSSRUWV RWKHUFUHDWLRQSDWWHUQVDQGFRPSUHKHQVLRQVHPSOR\LWHUDWLRQ LQ3\WKRQ$VVLJQLQJWRQHZNH\VJHQHUDWHVQHZHQWULHV $Q\LPPXWDEOHREMHFWFDQEHDNH\ HJVWULQJQXPEHUWX SOH  DQG FODVV LQVWDQFHV FDQ EH NH\V LI WKH\ LQKHULW KDVKLQJ SURWRFROPHWKRGV7XSOHNH\VVXSSRUWFRPSRXQGYDOXHV HJ adict[(M,D,Y)]ZLWKSDUHQWKHVHVRSWLRQDO 

Specific Built-in Types | 41

More free ebooks : http://fast-file.blogspot.com

{}

$QHPSW\GLFWLRQDU\ {'spam': 2, 'eggs': 3}

$WZRLWHPGLFWLRQDU\NH\V'spam'DQG'eggs' adict = { 'info': { 42: 1, type("): 2 }, 'spam': [] } 1HVWHGGLFWLRQDULHVadict['info'][42]IHWFKHV1 adict = dict(name='Bob', age=45, job=('mgr', 'dev'))

&UHDWHVDGLFWLRQDU\E\SDVVLQJNH\ZRUGDUJXPHQWVWRWKH W\SHFRQVWUXFWRU adict = dict(zip('abc', [1, 2, 3]))

&UHDWHVDGLFWLRQDU\E\SDVVLQJNH\YDOXHWXSOHVOLVWWRWKH W\SHFRQVWUXFWRU adict = dict([['a', 1], ['b', 2], ['c', 3]])

6DPHHIIHFWDVSULRUOLQHDQ\LWHUDEOHRINH\VDQGYDOXHV adict = {c: ord(c) for c in 'spam'}

'LFWLRQDU\ FRPSUHKHQVLRQ H[SUHVVLRQ 3\WKRQ   6HH £/LVWFRPSUHKHQVLRQH[SUHVVLRQV¤RQSDJHIRUV\QWD[

Operations 2SHUDWLRQVFRPSULVHDOOPDSSLQJRSHUDWLRQV VHH7DEOHRQ SDJH SOXVWKHIROORZLQJGLFWLRQDU\VSHFLILFPHWKRGV adict.keys()

$OONH\VLQadict,Q3\WKRQ;WKLVUHWXUQVDOLVW,Q3\ WKRQLWUHWXUQVDQLWHUDEOHYLHZREMHFWGHVFULEHGHDU OLHUfor k in adict:DOVRVXSSRUWVNH\VLWHUDWLRQ adict.values()

$OOVWRUHGYDOXHVLQ adict,Q3\WKRQ;WKLVUHWXUQVD OLVW,Q3\WKRQLWUHWXUQVDQLWHUDEOHYLHZREMHFWGH VFULEHGHDUOLHU adict.items()

7XSOHSDLUV(key, value)RQHIRUHDFKHQWU\LQadict,Q 3\WKRQ;WKLVUHWXUQVDOLVW,Q3\WKRQLWUHWXUQVDQ LWHUDEOHYLHZREMHFWGHVFULEHGHDUOLHU

42 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

adict.clear()

5HPRYHVDOOLWHPVIURPadict adict.copy()

5HWXUQVDVKDOORZ WRSOHYHO FRS\RIadict dict1.update(dict2) 0HUJHVDOORI dict2¦VHQWULHVLQWR dict1LQSODFHVLPLODU WRfor (k, v) in dict2.items(): dict1[k] = v,Q3\WKRQ

DOVRDFFHSWVDQLWHUDEOHRINH\YDOXHSDLUVDVZHOODV NH\ZRUGDUJXPHQWV dict.update(k1=v1, k2=v2)  adict.get(key [, default]) 6LPLODUWR adict[key]EXWUHWXUQV default RU NoneLIQR default LQVWHDGRIUDLVLQJDQH[FHSWLRQZKHQ keyLVQRW IRXQGLQadict adict.setdefault(key, [, default]) 6DPHDVadict.get(key, default)EXWDOVRDVVLJQVkeyWR defaultLILWLVQRWIRXQGLQadict adict.popitem()

5HPRYHVDQGUHWXUQVDQDUELWUDU\(key, value)SDLU adict.pop(k [, default]) 5HWXUQV adict[k]LI kLQ adict DQGUHPRYHV k HOVHUH WXUQVdefault adict.fromkeys(seq [, value])

&UHDWHVDQHZGLFWLRQDU\ZLWKNH\VIURP seqDQGYDOXHV VHWWRvalue 7KHIROORZLQJPHWKRGVDUHDYDLODEOHLQ3\WKRQ;RQO\ adict.has_key(k) 5HWXUQV TrueLI adictKDVDNH\ kRU FalseRWKHUZLVH,Q 3\WKRQ ; RQO\ WKLV PHWKRG LV HTXLYDOHQW WR k in adictEXWLVQRWJHQHUDOO\UHFRPPHQGHGLWLVUHPRYHG

LQ3\WKRQ adict.iteritems()adict.iterkeys()adict.itervalues()

5HWXUQVDQLWHUDWRURYHUNH\YDOXHSDLUVNH\VRQO\RUYDO XHVRQO\,Q3\WKRQWKHVHDUHUHPRYHGEHFDXVHkeys() values()DQGitems()UHWXUQLWHUDEOHYLHZREMHFWV

Specific Built-in Types | 43

More free ebooks : http://fast-file.blogspot.com

7KH IROORZLQJ RSHUDWLRQV DUH GHVFULEHG LQ 7DEOH  RQ SDJH EXWUHODWHWRPHWKRGVDERYH k in adict

5HWXUQVTrueLIadictKDVDNH\kRUFalseRWKHUZLVH5H SODFHVhas_key()LQ3\WKRQ for k in adict:

,WHUDWHV RYHU NH\V LQ adict DOO LWHUDWLRQ FRQWH[WV  'LFWLRQDU\VXSSRUWVGLUHFWLWHUDWLRQ for key in dictLV VLPLODUWR for key in dict.keys()7KHIRUPHUXVHVWKH GLFWLRQDU\REMHFW¦VNH\VLWHUDWRU,Q3\WKRQ;keys()UH WXUQVDQHZOLVWWKDWLQFXUVDVOLJKWRYHUKHDG,Q3\WKRQ  keys() UHWXUQV DQ LWHUDEOH YLHZ REMHFW LQVWHDG RI D SK\VLFDOO\VWRUHGOLVWPDNLQJERWKIRUPVHTXLYDOHQW

Tuples 7XSOHVDUHLPPXWDEOHDUUD\VRIREMHFWUHIHUHQFHVDFFHVVHGE\ RIIVHW

Literals 7XSOHV DUH ZULWWHQ DV FRPPDVHSDUDWHG VHULHV RI YDOXHV HQ FORVHG LQ SDUHQWKHVHV 7KH HQFORVLQJ SDUHQWKHVHV FDQ VRPH WLPHVEHRPLWWHG HJLQforORRSKHDGHUVDQG=DVVLJQPHQWV  ()

$QHPSW\WXSOH (0,)

$RQHLWHPWXSOH QRWDVLPSOHH[SUHVVLRQ  (0, 1, 2, 3)

$IRXULWHPWXSOH 0, 1, 2, 3

$QRWKHUIRXULWHPWXSOH VDPHDVSULRUOLQH QRWYDOLGLQ IXQFWLRQFDOOV atuple = ('spam', (42, 'eggs')) 1HVWHGWXSOHVatuple[1][1]IHWFKHV'eggs'

44 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

atuple = tuple('spam')

&UHDWHVDWXSOHRIDOOLWHPVLQDQ\LWHUDEOHE\FDOOLQJWKH W\SHFRQVWUXFWRUIXQFWLRQ

Operations $OOVHTXHQFHRSHUDWLRQV VHH7DEOHRQSDJH SOXVWKHIRO ORZLQJWXSOHVSHFLILFPHWKRGVLQ3\WKRQDQGODWHU atuple.index(x [, i [, j]])

5HWXUQV WKH LQGH[ RI WKH ILUVW RFFXUUHQFH RI REMHFW x LQ atupleUDLVHVDQH[FHSWLRQLIQRWIRXQG7KLVLVDVHDUFK PHWKRG,IiDQGjDUHSDVVHGLWUHWXUQVWKHVPDOOHVWkVXFK WKDWs[k] == xDQGi set2

7UXHVXEVHWDQGVXSHUVHWDOVRWHVWVWKDWset1DQGset2DUH QRWWKHVDPH set1 ^ set2set1.symmetric_difference(other)

6\PPHWULF GLIIHUHQFH QHZ VHW ZLWK HOHPHQWV LQ HLWKHU set1RUset2EXWQRWERWK set1 |= set2set1.update(other)

8SGDWHV QRWIRUIUR]HQVHWV DGGVLWHPVLQset2WRset1 set1.add(X) set1.remove(X) set1.discard(X) set1.pop() set1.clear()

8SGDWHV QRWIRUIUR]HQVHWV DGGVDQLWHPUHPRYHVDQ LWHPUHPRYHVDQLWHPLISUHVHQWUHPRYHVDQGUHWXUQVDQ DUELWUDU\LWHPUHPRYHVDOOLWHPV len(aset)

/HQJWKQXPEHUVLWHPVLQVHW for x in aset:

,WHUDWLRQDOOLWHUDWLRQFRQWH[WV aset.copy()

0DNHVDFRS\RIasetVDPHDVset(aset)

Other Common Types 3\WKRQ¦V FRUH W\SHV DOVR LQFOXGH %RROHDQV GHVFULEHG QH[W  None D SODFHKROGHU REMHFW  W\SHV DFFHVVHG ZLWK WKH type() EXLOWLQ IXQFWLRQ DQG DOZD\V FODVVHV LQ 3\WKRQ   DQG SURJUDPXQLW W\SHV VXFK DV IXQFWLRQV PRGXOHV DQG FODVVHV UXQWLPHREMHFWLQ3\WKRQ  Specific Built-in Types | 51

More free ebooks : http://fast-file.blogspot.com

Boolean 7KH%RROHDQW\SHQDPHGboolSURYLGHVWZRSUHGHILQHGFRQ VWDQWVQDPHGTrueDQGFalse DYDLODEOHVLQFHYHUVLRQ )RU PRVWSXUSRVHVWKHVHFRQVWDQWVFDQEHWUHDWHGDVWKRXJKWKH\ ZHUHSUHDVVLJQHGWRLQWHJHUVDQGUHVSHFWLYHO\ HJ True + 3\LHOGV4 +RZHYHUWKHboolW\SHLVDVXEFODVVRIWKHLQWHJHU W\SHintDQGFXVWRPL]HVLWWRSULQWLQVWDQFHVGLIIHUHQWO\ True SULQWVDV£7UXH¤QRW£¤DQGPD\EHXVHGDVDEXLOWLQQDPH LQORJLFDOWHVWV 

Type Conversions 7DEOHVDQGGHILQHFRPPRQEXLOWLQWRROVIRUFRQYHUWLQJ IURPRQHW\SHWRDQRWKHU 3\WKRQDOVRVXSSRUWVD long(S) WRORQJDQG`X`WRVWULQJFRQYHUWHUVUHPRYHGLQ3\WKRQ 7DEOH6HTXHQFHFRQYHUWHUV Converter

Converts from

Converts to

list(X),

String, tuple, any iterable

List

[n for n in X]a

a

tuple(X)

String, list, any iterable

Tuple

''.join(X)

Iterable of strings

String

The list comprehension form may be slower than list(). In Python 2.X only, map(None, X) has the same effect as list(X) in this context, though this form of map is removed in Python 3.0.

7DEOH6WULQJREMHFWFRQYHUWHUV Converter

Converts from

Converts to

eval(S)

String

Any object with a syntax (expression)

int(S [, base]),a

String or number

Integer, float

Any Python object

String (repr is as code, str is user-friendly)

float(S) repr(X), str(X)

52 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

a

Converter

Converts from

Converts to

F % X, F.format(X)

Objects with format codes

String

hex(X), oct(X), bin(X), str(X)

Integer types

Hexadecimal, octal, binary, decimal digit strings

ord(C), chr(I)

Character, integer code

Integer code, character

In version 2.2 and later, converter functions (e.g., int, float, str) also serve as class constructors and can be subclassed. In Python 3.0, all types are classes, and all classes are instances of the type class.

Statements and Syntax 7KLVVHFWLRQGHVFULEHVWKHUXOHVIRUV\QWD[DQGYDULDEOHQDPHV

Syntax Rules +HUHDUHWKHJHQHUDOUXOHVIRUZULWLQJ3\WKRQSURJUDPV &RQWUROIORZ 6WDWHPHQWVH[HFXWHRQHDIWHUDQRWKHUXQOHVVFRQWUROIORZ VWDWHPHQWVDUHXVHG ifwhileforraiseFDOOVHWF  %ORFNV $EORFNLVGHOLPLWHGE\LQGHQWLQJDOORILWVVWDWHPHQWVE\ WKHVDPHDPRXQWZLWKVSDFHVRUWDEV$WDEFRXQWVIRU HQRXJK VSDFHV WR PRYH WKH FROXPQ WR D PXOWLSOH RI  %ORFNVFDQDSSHDURQWKHVDPHOLQHDVDVWDWHPHQWKHDGHU LIWKH\DUHVLPSOHVWDWHPHQWV 6WDWHPHQWV $VWDWHPHQWHQGVDWWKHHQGRIDOLQHEXWFDQFRQWLQXH RYHUPXOWLSOHOLQHVLIDSK\VLFDOOLQHHQGVZLWKD \DQXQ FORVHG () [] RU {} SDLU RU DQ XQFORVHG WULSOHTXRWHG VWULQJ0XOWLSOHVLPSOHVWDWHPHQWVFDQDSSHDURQDOLQHLI WKH\DUHVHSDUDWHGZLWKDVHPLFRORQ ;  &RPPHQWV &RPPHQWV VWDUW ZLWK D # QRW LQ D VWULQJ FRQVWDQW  DQG VSDQWRWKHHQGRIWKHOLQH

Statements and Syntax | 53

More free ebooks : http://fast-file.blogspot.com

'RFXPHQWDWLRQVWULQJV ,IDIXQFWLRQPRGXOHILOHRUFODVVEHJLQVZLWKDVWULQJOLW HUDOLWLVVWRUHGLQWKHREMHFW¦V __doc__DWWULEXWH6HHWKH help()IXQFWLRQDQGWKH pydocPRGXOHDQGVFULSWLQWKH 3\WKRQ/LEUDU\5HIHUHQFHIRUDXWRPDWHGH[WUDFWLRQDQG GLVSOD\WRROV :KLWHVSDFH *HQHUDOO\ VLJQLILFDQW RQO\ WR WKH OHIW RI FRGH ZKHUH LQ GHQWDWLRQLVXVHGWRJURXSEORFNV%ODQNOLQHVDQGVSDFHV DUH RWKHUZLVH LJQRUHG H[FHSW DV WRNHQ VHSDUDWRUV DQG ZLWKLQVWULQJFRQVWDQWV

Name Rules 7KLV VHFWLRQ FRQWDLQV WKH UXOHV IRU XVHUGHILQHG QDPHV LH YDULDEOHV LQSURJUDPV

Name format 6WUXFWXUH 8VHUGHILQHGQDPHVVWDUWZLWKDOHWWHURUXQGHUVFRUH _  IROORZHGE\DQ\QXPEHURIOHWWHUVGLJLWVRUXQGHUVFRUHV 5HVHUYHGZRUGV 8VHUGHILQHG QDPHV FDQQRW EH WKH VDPH DV DQ\ 3\WKRQ UHVHUYHGZRUGOLVWHGLQ7DEOH® &DVHVHQVLWLYLW\ 8VHUGHILQHGQDPHVDQGUHVHUYHGZRUGVDUHDOZD\VFDVH VHQVLWLYH63$0VSDPDQG6SDPDUHGLIIHUHQWQDPHV 8QXVHGWRNHQV 3\WKRQGRHVQRWXVHWKHFKDUDFWHUV $DQG ?LQLWVV\QWD[ WKRXJKWKH\FDQDSSHDULQVWULQJFRQVWDQWVDQGFRPPHQWV DQG$LVVSHFLDOLQVWULQJWHPSODWHVXEVWLWXWLRQ

® ,Q WKH -\WKRQ -DYDEDVHG LPSOHPHQWDWLRQ XVHUGHILQHG QDPHV FDQ VRPHWLPHVEHWKHVDPHDVUHVHUYHGZRUGV

54 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

&UHDWLRQ 8VHUGHILQHGQDPHVDUHFUHDWHGE\DVVLJQPHQWEXWPXVW H[LVW ZKHQ UHIHUHQFHG HJ FRXQWHUV PXVW EH H[SOLFLWO\ LQLWLDOL]HGWR]HUR 6HHWKHVHFWLRQ£1DPHVSDFHDQG6FRSH 5XOHV¤RQSDJH 7DEOH3\WKRQUHVHUYHGZRUGV False

class

finally

is

return

None

continue

for

lambda

try

True

def

from

nonlocal

while

and

del

global

not

with

as

elif

if

or

yield

assert

else

import

pass

break

except

in

raise

NOTE ,Q3\WKRQprintDQG execDUHERWKUHVHUYHGZRUGV DVWKH\WDNHWKHIRUPRIVWDWHPHQWVQRWEXLOWLQIXQF WLRQV$OVRLQ3\WKRQnonlocalTrueDQGFalseDUH QRWUHVHUYHGZRUGVWKHILUVWRIWKHVHLVXQDYDLODEOHDQG WKHODWWHUWZRDUHVLPSO\EXLOWLQQDPHVwithDQGasDUH UHVHUYHGLQERWKDQGEXWQRWLQHDUOLHU;UH OHDVHV XQOHVV FRQWH[W PDQDJHUV DUH H[SOLFLWO\ HQDEOHG yieldLVUHVHUYHGDVRILWPRUSKHGIURPVWDWHPHQWWR H[SUHVVLRQODWHUEXWLVVWLOODUHVHUYHGZRUG

Name conventions ‡ 1DPHVWKDWEHJLQDQGHQGZLWKWZRXQGHUVFRUHV IRUH[ DPSOH__init__ KDYHDVSHFLDOPHDQLQJWRWKHLQWHUSUHWHU EXWDUHQRWUHVHUYHGZRUGV ‡ 1DPHV EHJLQQLQJ ZLWK RQH XQGHUVFRUH HJ _X DQG DVVLJQHG DW WKH WRS OHYHO RI D PRGXOH DUH QRW FRSLHG RXW E\ from...* LPSRUWV VHH DOVR WKH __all__ PRGXOH H[SRUW QDPHV OLVW PHQWLRQHG LQ WKH VHFWLRQV £7KH IURP 6WDWHPHQW¤ RQ SDJH  DQG Statements and Syntax | 55

More free ebooks : http://fast-file.blogspot.com

‡

‡

‡

‡

‡

£3VHXGRSULYDWH $WWULEXWHV¤ RQ SDJH   ,Q RWKHU FRQ WH[WVWKLVLVDQLQIRUPDOFRQYHQWLRQIRULQWHUQDOQDPHV 1DPHVEHJLQQLQJEXWQRWHQGLQJZLWKWZRXQGHUVFRUHV HJ__X ZLWKLQDclassVWDWHPHQWDUHSUHIL[HGZLWKWKH HQFORVLQJ FODVV¦V QDPH VHH £3VHXGRSULYDWH $WWULE XWHV¤RQSDJH  7KHQDPHWKDWLVMXVWDVLQJOHXQGHUVFRUH _ LVXVHGLQWKH LQWHUDFWLYHLQWHUSUHWHU RQO\ WRVWRUHWKHUHVXOWRIWKHODVW HYDOXDWLRQ %XLOWLQ IXQFWLRQ DQG H[FHSWLRQ QDPHV HJ open SyntaxError DUHQRWUHVHUYHGZRUGV7KH\OLYHLQWKHODVW VHDUFKHGVFRSHDQGFDQEHUHDVVLJQHGWRKLGHWKHEXLOWLQ PHDQLQJLQWKHFXUUHQWVFRSH HJopen=myfunction  &ODVV QDPHV FRPPRQO\ EHJLQ ZLWK DQ XSSHUFDVH OHWWHU HJMyClass DQGPRGXOHVZLWKDORZHUFDVHOHWWHU HJ mymodule  7KHILUVW OHIWPRVW DUJXPHQWLQDFODVVPHWKRGIXQFWLRQ LVXVXDOO\QDPHGself

Specific Statements 7KH IROORZLQJ VHFWLRQV GHVFULEH DOO 3\WKRQ VWDWHPHQWV (DFK VHFWLRQOLVWVWKHVWDWHPHQW¦VV\QWD[IRUPDWVIROORZHGE\XVDJH GHWDLOV)RUFRPSRXQGVWDWHPHQWVHDFKDSSHDUDQFHRIDVXLWH LQDVWDWHPHQWIRUPDWVWDQGVIRURQHRUPRUHRWKHUVWDWHPHQWV SRVVLEO\LQGHQWHGDVDEORFNXQGHUDKHDGHUOLQH$VXLWHPXVW EHLQGHQWHGXQGHUDKHDGHULILWFRQWDLQVDQRWKHUFRPSRXQG VWDWHPHQW ifwhileHWF RWKHUZLVHLWFDQDSSHDURQWKHVDPH OLQH DV WKH VWDWHPHQW KHDGHU 7KH IROORZLQJ DUH ERWK YDOLG FRQVWUXFWV if x < 42: print(x) while x: x = x − 1 if x < 42: print(x)

56 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

The Assignment Statement target = expression target1 = target2 = expression target1, target2 = expression1, expression2 target1 += expression target1, target2, ... = same-length-iterable (target1, target2, ...) = same-length-iterable [target1, target2, ...] = same-length-iterable target1, *target2, ... = matching–length-iterable

$VVLJQPHQWVVWRUHUHIHUHQFHVWRREMHFWVLQWDUJHWV([SUHVVLRQV \LHOG REMHFWV 7DUJHWV FDQ EH VLPSOH QDPHV X  TXDOLILHG DW WULEXWHV X.attr RULQGH[HVDQGVOLFHV X[i]X[i:j]  7KHVHFRQGIRUPDWDVVLJQVDQexpressionREMHFWWRHDFKWDUJHW 7KHWKLUGIRUPDWSDLUVWDUJHWVZLWKH[SUHVVLRQVOHIWWRULJKW 7KHODVWWKUHHIRUPDWVDVVLJQFRPSRQHQWVRIDQ\VHTXHQFH RU RWKHULWHUDEOH WRFRUUHVSRQGLQJWDUJHWVIURPOHIWWRULJKW7KH VHTXHQFHRULWHUDEOHRQWKHULJKWPXVWEHWKHVDPHOHQJWKEXW FDQEHDQ\W\SHXQOHVVDVLQJOHVWDUUHGQDPHDSSHDUVLQWKH WDUJHWVRQWKHOHIWWRFROOHFWDUELWUDULO\PDQ\LWHPV 3\WKRQ H[WHQGHGVHTXHQFHDVVLJQPHQWGLVFXVVHGDKHDG  target1, *target2, ... = iterable

Augmented assignment $VHWRIDGGLWLRQDODVVLJQPHQWVWDWHPHQWIRUPDWVOLVWHGLQ7D EOHDUHDYDLODEOH.QRZQDVDXJPHQWHGDVVLJQPHQWVWKHVH IRUPDWVLPSO\DELQDU\H[SUHVVLRQSOXVDQDVVLJQPHQW)RULQ VWDQFHWKHIROORZLQJWZRIRUPDWVDUHURXJKO\HTXLYDOHQW X = X + Y X += Y

+RZHYHUWKHUHIHUHQFHWRWDUJHWXLQWKHVHFRQGIRUPDWQHHGV WREHHYDOXDWHGRQO\RQFHDQGLQSODFHRSHUDWLRQVFDQEHDS SOLHG IRU PXWDEOHV DV DQ RSWLPL]DWLRQ HJ list1 += list2 DXWRPDWLFDOO\FDOOVlist1.extend(list2)LQVWHDGRIWKHVORZHU FRQFDWHQDWLRQRSHUDWLRQLPSOLHGE\ + &ODVVHVFDQRYHUORDG LQSODFHDVVLJQPHQWVZLWKPHWKRGQDPHVWKDWEHJLQZLWKDQ i HJ__iadd__IRU+=__add__IRU+ 7KHIRUPDWX //= Y IORRU GLYLVLRQ LVQHZDVRIYHUVLRQ Specific Statements | 57

More free ebooks : http://fast-file.blogspot.com

7DEOH$XJPHQWHGDVVLJQPHQWVWDWHPHQWV X += Y

X &= Y

X -= Y

X |= Y

X *= Y

X ^= Y

X /= Y

X >>= Y

X %= Y

X > a, b, c, d = [1, 2, 3, 4] >>> a, d (1, 4) >>> for (a, b, c) in [[1, 2, 3], [4, 5, 6]]: ... print(a, b, c) ... 1 2 3 4 5 6

,Q3\WKRQVHTXHQFHDVVLJQPHQWLVH[WHQGHGWRDOORZFRO OHFWLRQRIDUELWUDULO\PDQ\LWHPVE\SUHIL[LQJRQHYDULDEOHLQ WKHDVVLJQPHQWWDUJHWZLWKDVWDUZKHQXVHGVHTXHQFHOHQJWKV QHHGQRWPDWFK >>> a, *b = [1, 2, 3, 4] >>> a, b (1, [2, 3, 4]) >>> a, *b, c = [1, 2, 3, 4] >>> a, b, c (1, [2, 3], 4) >>> *a, b = [1, 2, 3, 4] >>> a, b ([1, 2, 3], 4) >>> for (a, *b) in [[1, 2, 3], [4, 5, 6]]: print(a, b) ... 1 [2, 3] 4 [5, 6]

58 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

The Expression Statement expression function([value, name=value, *name, **name...]) object.method([value, name=value, *name, **name...])

$Q\H[SUHVVLRQFDQDSSHDURQDOLQHE\LWVHOIDVDVWDWHPHQW EXWVWDWHPHQWVFDQQRWDSSHDUDVH[SUHVVLRQV ([SUHVVLRQVDUH FRPPRQO\ XVHG IRU FDOOLQJ IXQFWLRQV DQG PHWKRGV DQG IRU LQWHUDFWLYHPRGHSULQWLQJ([SUHVVLRQVWDWHPHQWVDUHDOVRWKH PRVW FRPPRQ FRGLQJ IRU yield H[SUHVVLRQV DQG 3\WKRQ  print()EXLOWLQIXQFWLRQFDOOV WKRXJKWKH\DUHGRFXPHQWHGDV VSHFLILFVWDWHPHQWVLQWKLVERRN 

Call syntax ,QIXQFWLRQDQGPHWKRGFDOOVDFWXDODUJXPHQWVDUHVHSDUDWHG E\FRPPDVDQGDUHQRUPDOO\PDWFKHGWRDUJXPHQWVLQIXQFWLRQ defKHDGHUVE\SRVLWLRQ&DOOVFDQRSWLRQDOO\OLVWVSHFLILFDUJX PHQWQDPHVLQIXQFWLRQVWRUHFHLYHSDVVHGYDOXHVE\XVLQJWKH name=value NH\ZRUG DUJXPHQW V\QWD[ .H\ZRUG DUJXPHQWV PDWFKE\QDPHLQVWHDGRISRVLWLRQ

Arbitrary arguments call syntax 6SHFLDOV\QWD[FDQEHXVHGLQIXQFWLRQDQGPHWKRGFDOODUJX PHQWOLVWVWRXQSDFNDUELWUDULO\PDQ\DUJXPHQWV,IpargsDQG kargs DUH D VHTXHQFH RU RWKHU LWHUDEOH  DQG D GLFWLRQDU\ UHVSHFWLYHO\ f(*pargs, **kargs)

7KLVIRUPDWFDOOVIXQFWLRQ fZLWKSRVLWLRQDODUJXPHQWVIURP LWHUDEOH pargs DQG NH\ZRUG DUJXPHQWV IURP GLFWLRQDU\ kargs)RULQVWDQFH >>> def f(a, b, c, d): print(a, b, c, d) ... >>> f(*[1, 2], **dict(c=3, d=4)) 1 2 3 4

7KLVV\QWD[LVLQWHQGHGWREHV\PPHWULFZLWKIXQFWLRQKHDGHU DUELWUDU\DUJXPHQWV\QWD[VXFKDV def f(*pargs **kargs),W LV DOVR IOH[LEOH VLQFH LW FDQ EH HDVLO\ FRPELQHG ZLWK RWKHU Specific Statements | 59

More free ebooks : http://fast-file.blogspot.com

SRVLWLRQDO DQG NH\ZRUG DUJXPHQWV HJ g(1, 2, foo=3, bar=4, *args, **kw)  ,Q3\WKRQ;WKHapply()EXLOWLQIXQFWLRQDFKLHYHVDVLPLODU HIIHFWEXWLVUHPRYHGDVRI3\WKRQ apply(f, pargs, kargs)

6HHDOVR£7KHGHI6WDWHPHQW¤RQSDJHIRUPRUHFDOOV\QWD[ GHWDLOV

The print Statement 3ULQWLQJWDNHVWKHIRUPRIDEXLOWLQIXQFWLRQFDOOLQ3\WKRQ ZKLFKLVFRPPRQO\FRGHGDVDQH[SUHVVLRQVWDWHPHQW RQDOLQH E\LWVHOI ,WVFDOOVLJQDWXUHLVDVIROORZV print([value [, value]*] [, sep=string] [, end=string] [, file=file])

(DFKvalueGHQRWHVDQREMHFWWREHSULQWHG7KLVFDOOLVFRQILJ XUHGE\LWVWKUHHNH\ZRUGRQO\DUJXPHQWV ‡ sepLVDVWULQJWRSODFHEHWZHHQYDOXHV GHIDXOWVWRDVSDFH ' '  ‡ endLVDVWULQJWRSODFHDWWKHHQGRIWKHWH[WSULQWHG GH IDXOWVWRDQHZOLQH'\n'  ‡ fileLVWKHILOHOLNHREMHFWWRZKLFKWH[WLVZULWWHQ GHIDXOWV WRVWDQGDUGRXWSXWsys.stdout  3DVVHPSW\RUFXVWRPVWULQJVWRVXSSUHVVVSDFHVHSDUDWRUVDQG OLQHIHHGVDQGSDVVDILOHRUILOHOLNHREMHFWWRUHGLUHFWRXWSXW LQ\RXUVFULSW >>> print(2 ** 32, 'spam') 4294967296 spam >>> print(2 ** 32, 'spam', sep='') 4294967296spam >>> print(2 ** 32, 'spam', end=' '); print(1, 2, 3) 4294967296 spam 1 2 3 >>> print(2 ** 32, 'spam', sep='', file=open('out', 'w'))

60 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

>>> open('out').read() '4294967296spam\n'

%HFDXVHE\GHIDXOWprintVLPSO\FDOOVWKHwritePHWKRGRIWKH REMHFW FXUUHQWO\ UHIHUHQFHG E\ sys.stdout WKH IROORZLQJ LV HTXLYDOHQWWRprint(X) import sys sys.stdout.write(str(X) + '\n')

7RUHGLUHFW printWH[WWRILOHVRUFODVVREMHFWVHLWKHUSDVVDQ\ REMHFWZLWKDwritePHWKRGWRWKHfileNH\ZRUGDUJXPHQWDV VKRZQHDUOLHURUUHDVVLJQsys.stdoutWRDQ\VXFKREMHFW sys.stdout = open('log', 'a') print('Warning-bad spam!')

# any object with a write() # goes to object's write()

%HFDXVHsys.stdoutFDQEHUHDVVLJQHGWKHfileNH\ZRUGDUJX PHQWLVQRWVWULFWO\QHHGHGKRZHYHULWFDQRIWHQDYRLGERWK H[SOLFLWwritePHWKRGFDOOVDQGVDYLQJDQGUHVWRULQJWKHRULJ LQDO sys.stdout YDOXH DURXQG D UHGLUHFWHG print ZKHQ WKH RULJLQDO VWUHDP LV VWLOO UHTXLUHG 6HH DOVR £%XLOWLQ )XQF WLRQV¤RQSDJH

Python 2.X print statements ,Q3\WKRQ;SULQWLQJLVDVSHFLILFVWDWHPHQWLQVWHDGRIDEXLOW LQIXQFWLRQRIWKHIROORZLQJIRUP print [value [, value]* [,]] print >> file [, value [, value]* [,]]

7KH3\WKRQ; printVWDWHPHQWGLVSOD\VWKHSULQWDEOHUHSUH VHQWDWLRQRIYDOXHVRQWKHstdoutVWUHDP WKHFXUUHQWVHWWLQJRI sys.stdout  DQG DGGV VSDFHV EHWZHHQ YDOXHV 7KH WUDLOLQJ FRPPDVXSSUHVVHVWKHOLQHIHHGWKDWLVQRUPDOO\DGGHGDWWKH HQGRIDOLVWDQGLVHTXLYDOHQWWRXVLQJend=' 'LQ3\WKRQ >>> print 2 ** 32, 'spam' 4294967296 spam >>> print 2 ** 32, 'spam',; print 1, 2, 3 4294967296 spam 1 2 3

Specific Statements | 61

More free ebooks : http://fast-file.blogspot.com

7KH3\WKRQ;printVWDWHPHQWFDQDOVRQDPHDQRSHQRXWSXW ILOHOLNHREMHFWWREHWKHWDUJHWRIWKHSULQWHGWH[WLQVWHDGRI sys.stdout fileobj = open('log', 'a') print >> fileobj, "Warning-bad spam!"

,IWKHILOHREMHFWLV None sys.stdoutLVXVHG7KLV3\WKRQ; >>V\QWD[LVHTXLYDOHQWWRWKHfile=FNH\ZRUGDUJXPHQWLQ3\ WKRQ  7KHUH LV QR HTXLYDOHQW WR sep=S LQ 3\WKRQ ¦V VWDWHPHQW 7RXVHWKH3\WKRQSULQWLQJIXQFWLRQLQ3\WKRQ;UXQWKH IROORZLQJ from __future__ import print_function

The if Statement if test: suite [elif test: suite]* [else: suite]

7KH if VWDWHPHQW VHOHFWV IURP DPRQJ RQH RU PRUH DFWLRQV VWDWHPHQWEORFNV DQGLWUXQVWKHVXLWHDVVRFLDWHGZLWKWKH ILUVWifRUelifWHVWWKDWLVtrueRUWKHelseVXLWHLIDOODUHfalse

The while Statement while test: suite [else: suite]

7KH whileORRSLVDJHQHUDOORRSWKDWNHHSVUXQQLQJWKHILUVW VXLWHZKLOHWKHWHVWDWWKHWRSLVWUXH,WUXQVWKHelseVXLWHLIWKH ORRSH[LWVZLWKRXWKLWWLQJDbreakVWDWHPHQW

62 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

The for Statement for target in iterable: suite [else: suite]

7KH for ORRS LV D VHTXHQFH RU RWKHU LWHUDEOH  LWHUDWLRQ WKDW DVVLJQVLWHPVLQiterableWRtargetDQGUXQVWKHILUVWVXLWHIRU HDFK7KH forVWDWHPHQWUXQVWKH elseVXLWHLIWKHORRSH[LWV ZLWKRXWKLWWLQJDbreakVWDWHPHQWtargetFDQEHDQ\WKLQJWKDW FDQDSSHDURQWKHOHIWVLGHRIDQ=DVVLJQPHQWVWDWHPHQW HJ for (x, y) in tuplelist:  6LQFH3\WKRQWKLVZRUNVE\ILUVWWU\LQJWRREWDLQDQLWHUD WRUREMHFWIZLWKiter(iterable)DQGWKHQFDOOLQJWKDWREMHFW¦V I.__next__()PHWKRGUHSHDWHGO\XQWLO StopIterationLVUDLVHG I.__next__()LVQDPHGI.next()LQ3\WKRQ VHH£7KH\LHOG 6WDWHPHQW¤ RQ SDJH  IRU PRUH RQ LWHUDWLRQ ,Q HDUOLHU YHU VLRQV RU LI QR LWHUDWRU REMHFW FDQ EH REWDLQHG HJ QR __iter__PHWKRGLVGHILQHG WKLVZRUNVLQVWHDGE\UHSHDWHGO\ LQGH[LQJ iterable DW VXFFHVVLYHO\ KLJKHU RIIVHWV XQWLO DQ IndexErrorLVUDLVHG

The pass Statement pass

7KLVLVDGRQRWKLQJSODFHKROGHUVWDWHPHQWDQGLVXVHGZKHQ V\QWDFWLFDOO\ QHFHVVDU\ ,Q 3\WKRQ ; RQO\ HOOLSVHV   FDQ DFKLHYHVLPLODUHIIHFWV

The break Statement break

7KLVLPPHGLDWHO\H[LWVWKHFORVHVWHQFORVLQJwhileRUforORRS VWDWHPHQWVNLSSLQJLWVDVVRFLDWHGelse LIDQ\ 

Specific Statements | 63

More free ebooks : http://fast-file.blogspot.com

The continue Statement continue

7KLV LPPHGLDWHO\ JRHV WR WKH WRS RI WKH FORVHVW HQFORVLQJ whileRUforORRSVWDWHPHQWLWUHVXPHVLQWKHORRSKHDGHUOLQH

The del Statement del del del del

name name[i] name[i:j:k] name.attribute

7KHdelVWDWHPHQWGHOHWHVQDPHVLWHPVVOLFHVDQGDWWULEXWHV DVZHOODVUHPRYHVELQGLQJV,QWKHODVWWKUHHIRUPV nameFDQ DFWXDOO\ EH DQ\ H[SUHVVLRQ ZLWK SDUHQWKHVHV LI UHTXLUHG IRU SULRULW\ )RULQVWDQFHdel a.b()[1].c.d

The def Statement def name([arg,... arg=value,... *arg, **arg]): suite

7KHdefVWDWHPHQWPDNHVQHZIXQFWLRQV,WFUHDWHVDIXQFWLRQ REMHFWDQGDVVLJQVLWWRYDULDEOH name(DFKFDOOWRDIXQFWLRQ REMHFWJHQHUDWHVDQHZORFDOVFRSHZKHUHDVVLJQHGQDPHVDUH ORFDO WR WKH IXQFWLRQ FDOO E\ GHIDXOW XQOHVV GHFODUHG JOREDO  6HH DOVR WKH VHFWLRQ £1DPHVSDFH DQG 6FRSH 5XOHV¤RQSDJH$UJXPHQWVDUHSDVVHGE\DVVLJQPHQWLQ DdefKHDGHUWKH\FDQEHGHILQHGE\DQ\RIWKHIRXUIRUPDWVLQ 7DEOH 7KHDUJXPHQWIRUPVLQ7DEOHFDQDOVREHXVHGLQDIXQFWLRQ FDOOZKHUHWKH\DUHLQWHUSUHWHGDVVKRZQLQ7DEOH VHH£7KH ([SUHVVLRQ6WDWHPHQW¤RQSDJHIRUPRUHRQIXQFWLRQFDOO V\QWD[ 

64 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

7DEOH$UJXPHQWIRUPDWVLQGHILQLWLRQV Argument format

Interpretation

arg

Matched by name or position

arg=value

Default value if arg is not passed

*arg

Collects extra positional args as a new tuple

**arg

Collects extra keyword args passed as a new dictionary

*name, arg[=value]

Python 3.0 keyword-only arguments after *

*, arg[=value]

Same as prior line

7DEOH$UJXPHQWIRUPDWVLQFDOOV Argument format

Interpretation

arg

Positional argument

arg=value

Keyword (match by name) argument

*arg

Sequence (or other iterable) of positional arguments

**arg

Dictionary of keyword arguments

Python 3.0 keyword-only arguments 3\WKRQJHQHUDOL]HVIXQFWLRQGHILQLWLRQWRDOORZNH\ZRUG RQO\DUJXPHQWVZKLFKPXVWEHSDVVHGE\NH\ZRUGDQGDUH UHTXLUHGLIQRWFRGHGZLWKGHIDXOWV.H\ZRUGRQO\DUJXPHQWV DUHFRGHGDIWHUWKH*ZKLFKPD\DSSHDUZLWKRXWDQDPHLIWKHUH DUHNH\ZRUGRQO\DUJXPHQWVEXWQRWDUELWUDU\SRVLWLRQDOV >>> def f(a, *b, c): print(a, b, c) ... >>> f(1, 2, c=3) 1 (2,) 3

# c required keyword

>>> def f(a, *, c=None): print(a, c) # c optional keyword ... >>> f(1) 1 None >>> f(1, c='spam') 1 spam

Specific Statements | 65

More free ebooks : http://fast-file.blogspot.com

Python 3.0 function annotations 3\WKRQDOVRJHQHUDOL]HVIXQFWLRQGHILQLWLRQWRDOORZDUJX PHQWVDQGUHWXUQYDOXHVWREHDQQRWDWHGZLWKREMHFWYDOXHVIRU XVHLQH[WHQVLRQV$QQRWDWLRQVDUHFRGHGDV :valueDIWHUWKH DUJXPHQWQDPHDQGEHIRUHDGHIDXOWDQG->valueDIWHUWKHDU JXPHQWOLVW7KH\DUHFROOHFWHGLQWRDQ__annotations__DWWULE XWHEXWDUHQRWRWKHUZLVHWUHDWHGDVVSHFLDOE\3\WKRQLWVHOI >>> def f(a:99, b:'spam'=None) -> float: ... print(a, b) ... >>> f(88) 88 None >>> f.__annotations__ {'a': 99, 'b': 'spam', 'return': }

lambda expressions )XQFWLRQVFDQDOVREHFUHDWHGZLWKWKHlambdaH[SUHVVLRQIRUP ZKLFKFUHDWHVDQHZIXQFWLRQREMHFWDQGUHWXUQVLWWREHFDOOHG ODWHULQVWHDGRIDVVLJQLQJLWWRDQDPH lambda arg, arg,...: expression

,QlambdaargLVDVLQdefexpressionLVWKHLPSOLHGUHWXUQYDOXH RIODWHUFDOOV%HFDXVHlambdaLVDQH[SUHVVLRQQRWDVWDWHPHQW LWFDQEHXVHGLQSODFHVWKDWD defFDQQRW HJZLWKLQDGLF WLRQDU\OLWHUDOH[SUHVVLRQRUDQDUJXPHQWOLVWRIDIXQFWLRQFDOO  %HFDXVH lambdaFRPSXWHVDVLQJOHH[SUHVVLRQLQVWHDGRIUXQ QLQJVWDWHPHQWVLWLVQRWLQWHQGHGIRUFRPSOH[IXQFWLRQV

Defaults and attributes 0XWDEOH GHIDXOW DUJXPHQW YDOXHV DUH HYDOXDWHG RQFH DW def VWDWHPHQWWLPHQRWRQHDFKFDOODQGVRFDQUHWDLQVWDWHEH WZHHQFDOOV+RZHYHUVRPHFRQVLGHUWKLVEHKDYLRUWREHDFDY HDWDQGFODVVHVDQGHQFORVLQJVFRSHUHIHUHQFHVDUHRIWHQEHWWHU VWDWHUHWHQWLRQWRROVXVHNoneGHIDXOWVIRUPXWDEOHDQGH[SOLFLW WHVWVWRDYRLGFKDQJHVDVVKRZQLQWKHIROORZLQJ¦VFRPPHQWV >>> def grow(a, b=[]): ... b.append(a) ... print(b)

66 | Python Pocket Reference

# ..., b=None) # if b == None: b = []

More free ebooks : http://fast-file.blogspot.com

... >>> grow(1); grow(2) [1] [1, 2]

%RWK3\WKRQ;DQGDOVRVXSSRUWDWWDFKPHQWRIDUELWUDU\ DWWULEXWHV WR IXQFWLRQV DV DQRWKHU IRUP RI VWDWH UHWHQWLRQ WKRXJK DWWULEXWHV VXSSRUW RQO\ SHUIXQFWLRQREMHFW VWDWH ZKLFKLVRQO\SHUFDOOLIHDFKFDOOJHQHUDWHVDQHZIXQFWLRQ  >>> grow.food = 'spam' >>> grow.food 'spam'

Function and method decorators $VRI3\WKRQIXQFWLRQGHILQLWLRQVFDQEHSUHFHGHGE\D GHFODUDWLRQ V\QWD[ WKDW GHVFULEHV WKH IXQFWLRQ WKDW IROORZV .QRZQDVGHFRUDWRUVDQGFRGHGZLWKDQ@FKDUDFWHUWKHVHGHF ODUDWLRQVSURYLGHH[SOLFLWV\QWD[IRUIXQFWLRQDOWHFKQLTXHV7KH IXQFWLRQGHFRUDWRUV\QWD[ @decorator def F(): ...

LVHTXLYDOHQWWRWKLVPDQXDOQDPHUHELQGLQJ def F(): ... F = decorator(F)

7KHHIIHFWLVWRUHELQGWKHIXQFWLRQQDPHWRWKHUHVXOWRISDVVLQJ WKHIXQFWLRQWKURXJKWKHGHFRUDWRUFDOODEOH)XQFWLRQGHFRUD WRUVPD\EHXVHGWRPDQDJHIXQFWLRQVRUODWHUFDOOVPDGHWR WKHP E\XVLQJSUR[\REMHFWV 'HFRUDWRUVPD\EHDSSOLHGWR DQ\IXQFWLRQGHILQLWLRQLQFOXGLQJPHWKRGVLQVLGHDFODVV class C: @decorator def M(): ...

# same as M = decorator(M)

0RUHJHQHUDOO\WKHIROORZLQJQHVWHGGHFRUDWLRQ @A @B

Specific Statements | 67

More free ebooks : http://fast-file.blogspot.com

@C def f(): ...

LVHTXLYDOHQWWRWKHIROORZLQJQRQGHFRUDWRUFRGH def f(): ... f = A(B(C(f)))

'HFRUDWRUVPD\DOVRWDNHDUJXPHQWOLVWV @spam(1,2,3) def f(): ...

,Q WKLV FDVH spam PXVW EH D IXQFWLRQ UHWXUQLQJ D IXQFWLRQ NQRZQDVDIDFWRU\IXQFWLRQ LWVUHVXOWLVXVHGDVWKHDFWXDO GHFRUDWRU'HFRUDWRUVPXVWDSSHDURQWKHOLQHEHIRUHDIXQF WLRQGHILQLWLRQDQGFDQQRWEHRQWKHVDPHOLQH HJ @A def f(): ...LVLOOHJDO  %HFDXVHWKH\DFFHSWDQGUHWXUQFDOODEOHVVRPHEXLOWLQIXQF WLRQV LQFOXGLQJ property() staticmethod() DQG classmethod()PD\EHXVHGDVIXQFWLRQGHFRUDWRUV VHH£%XLOW LQ)XQFWLRQV¤RQSDJH 'HFRUDWRUV\QWD[LVDOVRVXSSRU WHGIRUFODVVHVLQ3\WKRQDQGDQGODWHUVHH£7KHFODVV 6WDWHPHQW¤RQSDJH

The return Statement return [expression]

7KHreturnVWDWHPHQWH[LWVWKHHQFORVLQJIXQFWLRQDQGUHWXUQV DQexpressionYDOXHDVWKHUHVXOWRIWKHFDOOWRWKHIXQFWLRQ7KH expressionGHIDXOWVWRNoneLILW¦VRPLWWHG+LQWUHWXUQDWXSOH IRUPXOWLSOHYDOXHIXQFWLRQUHVXOWV

The yield Statement yield expression

7KHyieldH[SUHVVLRQFRPPRQO\FRGHGDVDQH[SUHVVLRQVWDWH PHQW RQDOLQHE\LWVHOI VXVSHQGVIXQFWLRQVWDWHDQGUHWXUQV DQexpression2QWKHQH[WLWHUDWLRQWKHIXQFWLRQ¦VSULRUVWDWH LVUHVWRUHGDQGFRQWUROUHVXPHVLPPHGLDWHO\DIWHUWKH yield

68 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

VWDWHPHQW 8VH D return VWDWHPHQW ZLWK QR YDOXH WR HQG WKH LWHUDWLRQRUVLPSO\IDOORIIWKHHQGRIWKHIXQFWLRQ def generateSquares(N): for i in range(N): yield i ** 2 >>> G = generateSquares(5) >>> list(G) [0, 1, 4, 9, 16]

# force results generation

:KHQXVHGDVDQH[SUHVVLRQ yieldUHWXUQVWKHREMHFWSDVVHG WRWKHJHQHUDWRU¦V send()PHWKRGDWWKHFDOOHU HJA = yield X DQGPXVWEHHQFORVHGLQSDUHQWKHVLVXQOHVVLWLVWKHRQO\ LWHPRQWKHULJKWRI= HJA = (yield X) + 42 ,QWKLVPRGH YDOXHVDUHVHQWWRDJHQHUDWRUE\FDOOLQJsend(value)WKHJHQ HUDWRULVUHVXPHGDQGWKH yieldH[SUHVVLRQUHWXUQV value,I WKHUHJXODU __next__()PHWKRGRU next()EXLOWLQIXQFWLRQLV FDOOHGWRDGYDQFHyieldUHWXUQVNone *HQHUDWRUVDOVRKDYHDthrow(type)PHWKRGWRUDLVHDQH[FHS WLRQ LQVLGH WKH JHQHUDWRU DW WKH ODWHVW yield DQG D close() PHWKRGWKDWUDLVHVDQHZ GeneratorExitH[FHSWLRQLQVLGHWKH JHQHUDWRU WR WHUPLQDWH WKH LWHUDWLRQ yield LV VWDQGDUG DV RI YHUVLRQDQGODWHUJHQHUDWRU send() throw()DQG close() PHWKRGVDUHDYDLODEOHDVRI3\WKRQ

Generators and iterators )XQFWLRQV FRQWDLQLQJ D yield VWDWHPHQW DUH FRPSLOHG DV JHQHUDWRUV ZKHQ FDOOHG WKH\ UHWXUQ D JHQHUDWRU REMHFW WKDW VXSSRUWVWKHLWHUDWRUSURWRFROWRSURGXFHUHVXOWVRQGHPDQG ,WHUDWRUVDUHREMHFWVUHWXUQHGE\WKHiter(X)EXLOWLQIXQFWLRQ WKH\GHILQHD__next__()PHWKRGZKLFKUHWXUQVWKHQH[WLWHP LQWKHLWHUDWLRQRUUDLVHVDStopIterationH[FHSWLRQWRHQGWKH LWHUDWLRQ $OOLWHUDWLRQFRQWH[WVLQFOXGLQJforORRSVDQGFRPSUHKHQVLRQV DXWRPDWLFDOO\XVHWKHLWHUDWLRQSURWRFROWRVWHSWKURXJKFRO OHFWLRQV,QDGGLWLRQWKH next(I)EXLOWLQIXQFWLRQDXWRPDWL FDOO\FDOOVI.__next__()WRVLPSOLI\PDQXDOLWHUDWLRQORRSV

Specific Statements | 69

More free ebooks : http://fast-file.blogspot.com

&ODVVHV FDQ SURYLGH DQ __iter__() PHWKRG WR LQWHUFHSW WKH iter(X) EXLOWLQ IXQFWLRQ FDOO LI GHILQHG LWV UHVXOW KDV D __next__() PHWKRG XVHG WR VWHS WKURXJK UHVXOWV LQ LWHUDWLRQ FRQWH[WV,IQR__iter__()LVGHILQHGWKH__getitem__()LQGH[ LQJPHWKRGLVXVHGDVDIDOOEDFNWRLWHUDWHXQWLOIndexError ,Q3\WKRQ;WKH I.__next__()PHWKRGLVQDPHG I.next() EXWLWHUDWLRQZRUNVWKHVDPHRWKHUZLVH7KH next()IXQFWLRQ FDOOVWKHI.next()PHWKRGLQ6HHDOVR£*HQHUDWRUH[SUHV VLRQV¤RQSDJHIRUUHODWHGWRROV

The global Statement global name [, name]*

7KH globalVWDWHPHQWLVDQDPHVSDFHGHFODUDWLRQZKHQXVHG LQVLGHDFODVVRUIXQFWLRQGHILQLWLRQVWDWHPHQWLWFDXVHVDOODS SHDUDQFHVRInameLQWKDWFRQWH[WWREHWUHDWHGDVUHIHUHQFHVWR DJOREDO PRGXOHOHYHO YDULDEOHRIWKDWQDPH¢ZKHWKHUnameLV DVVLJQHGRUQRWDQGZKHWKHUnameDOUHDG\H[LVWVRUQRW 7KLVVWDWHPHQWDOORZVJOREDOVWREHFUHDWHGRUFKDQJHGZLWKLQ DIXQFWLRQRUFODVV%HFDXVHRI3\WKRQ¦VVFRSHUXOHV\RXQHHG WR GHFODUH RQO\ JOREDO QDPHV WKDW DUH DVVLJQHG XQGHFODUHG QDPHVDUHPDGHORFDOLIDVVLJQHGEXWJOREDOUHIHUHQFHVDUHDX WRPDWLFDOO\ORFDWHGLQWKHHQFORVLQJPRGXOH6HHDOVR£1DPH VSDFHDQG6FRSH5XOHV¤RQSDJH

The nonlocal Statement nonlocal name [, name]*

$YDLODEOHLQ3\WKRQRQO\ 7KHnonlocalVWDWHPHQWLVDQDPHVSDFHGHFODUDWLRQZKHQXVHG LQVLGHDQHVWHGIXQFWLRQLWFDXVHVDOODSSHDUDQFHVRI nameLQ WKDWFRQWH[WWREHWUHDWHGDVUHIHUHQFHVWRDORFDOYDULDEOHRI WKDWQDPHLQDQHQFORVLQJIXQFWLRQ¦VVFRSH¢ZKHWKHU nameLV DVVLJQHGRUQRW namePXVWH[LVWLQDQHQFORVLQJIXQFWLRQWKLVVWDWHPHQWDOORZV

LW WR EH FKDQJHG E\ D QHVWHG IXQFWLRQ %HFDXVH RI 3\WKRQ¦V 70 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

VFRSHUXOHV\RXQHHGWRGHFODUHRQO\QRQORFDOQDPHVWKDWDUH DVVLJQHG XQGHFODUHG QDPHV DUH PDGH ORFDO LI DVVLJQHG EXW QRQORFDO UHIHUHQFHV DUH DXWRPDWLFDOO\ ORFDWHG LQ HQFORVLQJ IXQFWLRQV 6HH DOVR £1DPHVSDFH DQG 6FRSH 5XOHV¤RQSDJH

The import Statement import module [, module]* import [package.]* module [, [package.]* module]* import [package.]* module as name [, [package.]*module as name]*

7KH import VWDWHPHQW SURYLGHV PRGXOH DFFHVV LW LPSRUWV D PRGXOHDVDZKROH0RGXOHVLQWXUQFRQWDLQQDPHVIHWFKHGE\ TXDOLILFDWLRQ HJmodule.attribute $VVLJQPHQWVDWWKHWRS OHYHORID3\WKRQILOHFUHDWHPRGXOHREMHFWDWWULEXWHV7KH as FODXVHDVVLJQVDYDULDEOH nameWRWKHLPSRUWHGPRGXOHREMHFW LWLVXVHIXOWRSURYLGHVKRUWHUV\QRQ\PVIRUORQJPRGXOHQDPHV moduleQDPHVWKHWDUJHWPRGXOH¢XVXDOO\D3\WKRQVRXUFHILOH

RUFRPSLOHGPRGXOH¢ZKLFKPXVWEHORFDWHGLQDGLUHFWRU\LQ sys.path7KH moduleLVJLYHQZLWKRXWLWVILOHQDPHVXIIL[ S\ DQGRWKHUH[WHQVLRQVDUHRPLWWHG 7KH sys.pathPRGXOHLP SRUWVHDUFKSDWKLVDGLUHFWRU\OLVWLQLWLDOL]HGIURPWKHSURJUDP¦V WRSOHYHOGLUHFWRU\PYTHONPATHVHWWLQJV.pthSDWKILOHFRQWHQWV DQG3\WKRQGHIDXOWV ,PSRUWRSHUDWLRQVFRPSLOHDILOH¦VVRXUFHWRE\WHFRGHLIQHHGHG DQGVDYHLWLQDS\FILOHLISRVVLEOH WKHQH[HFXWHWKHFRPSLOHG FRGHIURPWRSWRERWWRPWRJHQHUDWHPRGXOHREMHFWDWWULEXWHV E\DVVLJQPHQW8VHWKHimp.reload()EXLOWLQIXQFWLRQWRIRUFH UHFRPSLODWLRQDQGH[HFXWLRQRIDOUHDG\ORDGHGPRGXOHVVHH DOVR __import__XVHGE\ importLQWKHVHFWLRQ£%XLOWLQ)XQF WLRQV¤RQSDJH ,Q WKH -\WKRQ LPSOHPHQWDWLRQ LPSRUWV FDQ DOVR QDPH -DYD FODVVOLEUDULHV-\WKRQJHQHUDWHVD3\WKRQPRGXOHZUDSSHUWKDW LQWHUIDFHVZLWKWKH-DYDOLEUDU\,QVWDQGDUG&3\WKRQLPSRUWV FDQDOVRORDGFRPSLOHG&DQG&H[WHQVLRQV

Specific Statements | 71

More free ebooks : http://fast-file.blogspot.com

Package imports ,I XVHG WKH package SUHIL[ QDPHV JLYH HQFORVLQJ GLUHFWRU\ QDPHVDQGPRGXOHGRWWHGSDWKVUHIOHFWGLUHFWRU\KLHUDUFKLHV $QLPSRUWRIWKHIRUP import dir1.dir2.modJHQHUDOO\ORDGV WKHPRGXOHILOHDWGLUHFWRU\SDWKGLUGLUPRGS\ZKHUHGLU PXVWEHFRQWDLQHGE\DGLUHFWRU\OLVWHGRQWKHPRGXOHVHDUFK SDWKsys.path (DFKGLUHFWRU\OLVWHGLQDQLPSRUWVWDWHPHQWPXVWKDYHD SRV VLEO\HPSW\ __init__.pyILOHWKDWVHUYHVDVWKHGLUHFWRU\OHYHO¦V PRGXOHQDPHVSDFH7KLVILOHLVUXQRQWKHILUVWLPSRUWWKURXJK WKHGLUHFWRU\DQGDOOQDPHVDVVLJQHGLQ __init__.pyILOHVEH FRPH DWWULEXWHV RI WKH GLUHFWRU\¦V PRGXOH REMHFW 'LUHFWRU\ SDFNDJHVFDQUHVROYHFRQIOLFWVFDXVHGE\WKHOLQHDUQDWXUHRI PYTHONPATH 6HHDOVR£3DFNDJHUHODWLYHLPSRUWV\QWD[¤RQSDJH

The from Statement from from from from

[package.]* [package.]* [package.]* [package.]*

module module module module

import import import import

name [, name]* * name as othername (name1, name2, ...)

7KHfromVWDWHPHQWLPSRUWVYDULDEOHQDPHVIURPDPRGXOHVR WKDW\RXFDQXVHWKRVHQDPHVODWHUZLWKRXWWKHQHHGWRTXDOLI\ WKHPZLWKWKHLUPRGXOHQDPH7KHfrom mod import *IRUPDW FRSLHVDOOQDPHVDVVLJQHGDWWKHWRSOHYHORIWKHPRGXOHH[FHSW QDPHVZLWKDVLQJOHOHDGLQJXQGHUVFRUHRUQDPHVQRWOLVWHGLQ WKHPRGXOH¦V__all__OLVWRIVWULQJVDWWULEXWH LIGHILQHG  ,I XVHG WKH as FODXVH FUHDWHV D QDPH V\QRQ\P ,I XVHG packageLPSRUWSDWKVZRUNWKHVDPHDVLQ importVWDWHPHQWV HJ from dir1.dir2.mod import X  EXW WKH SDFNDJH SDWK QHHGVWREHOLVWHGRQO\LQWKH fromLWVHOI'XHWRQHZVFRSLQJ UXOHVWKH *IRUPDWJHQHUDWHVZDUQLQJVLQYHUVLRQLILWDS SHDUVQHVWHGLQDIXQFWLRQRUFODVV WKLVJHQHUDWHVHUURUVLQ3\ WKRQ 

72 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

$VRI3\WKRQWKHQDPHVEHLQJLPSRUWHGIURPDPRGXOHFDQ EHHQFORVHGLQSDUHQWKHVHVWRVSDQPXOWLSOHOLQHVZLWKRXWEDFN VODVKHV$VRI3\WKRQfrom module import *IRUPLVLQYDOLG ZLWKLQ D IXQFWLRQ EHFDXVH LW PDNHV LW LPSRVVLEOH WR FODVVLI\ QDPHVFRSHVDWGHILQLWLRQWLPH 7KH fromVWDWHPHQWLVDOVRXVHGWRHQDEOHIXWXUH EXWVWLOOH[ SHULPHQWDO ODQJXDJHDGGLWLRQVZLWK from __future__ import featurename 7KLV IRUPDW PXVW DSSHDU RQO\ DW WKH WRS RI D PRGXOHILOH SUHFHGHGRQO\E\DQRSWLRQDOGRFVWULQJ 

Package relative import syntax ,Q 3\WKRQ  WKH from VWDWHPHQW EXW QRW import  PD\ XVH OHDGLQJGRWVLQPRGXOHQDPHVWRVSHFLI\WKDWLPSRUWVEHUHOD WLYHWRWKHSDFNDJHGLUHFWRU\LQZKLFKWKHLPSRUWLQJPRGXOH UHVLGHV from from from from from

module import name [, name]* . import module [, module]* .module import name [, name]* .. import module [, module]* ..module import name [, name]*

# # # # #

sys.path: abs pkg dir only: pkg dir only: parent dir in parent dir in

rel rel pkg pkg

7KH OHDGLQJGRWV V\QWD[ ZRUNV WR PDNH LPSRUWV H[SOLFLWO\ SDFNDJHUHODWLYHLQERWK3\WKRQDQG)RULPSRUWVZLWK RXWWKHGRWVV\QWD[WKHSDFNDJH¦VRZQGLUHFWRU\LVVHDUFKHG ILUVWLQ3\WKRQEXWQRWLQ3\WKRQ7RHQDEOH3\WKRQ SDFNDJHLPSRUWVHPDQWLFVLQ3\WKRQXVH from __future__ import

absolute_import

$EVROXWHSDFNDJHLPSRUWVUHODWLYHWRDGLUHFWRU\RQsys.path DUHJHQHUDOO\SUHIHUUHGRYHUERWKLPSOLFLWSDFNDJHUHODWLYHLP SRUWVLQ3\WKRQ;DQGH[SOLFLWSDFNDJHUHODWLYHLPSRUWV\Q WD[LQERWK3\WKRQ;DQG

The class Statement class name [ ( super [, super]* [, metaclass=M] ) ]: suite

Specific Statements | 73

More free ebooks : http://fast-file.blogspot.com

7KH classVWDWHPHQWPDNHVQHZFODVVREMHFWVZKLFKDUHIDF WRULHVIRULQVWDQFHREMHFWV7KHQHZFODVVREMHFWLQKHULWVIURP HDFKOLVWHG superFODVVLQWKHRUGHUJLYHQDQGLVDVVLJQHGWR YDULDEOHname7KHclassVWDWHPHQWLQWURGXFHVDQHZORFDOQDPH VFRSHDQGDOOQDPHVDVVLJQHGLQWKHclassVWDWHPHQWJHQHUDWH FODVVREMHFWDWWULEXWHVVKDUHGE\DOOLQVWDQFHVRIWKHFODVV ,PSRUWDQW FODVV IHDWXUHV LQFOXGH WKH IROORZLQJ VHH DOVR WKH VHFWLRQV £2EMHFW2ULHQWHG 3URJUDPPLQJ¤ RQ SDJH  DQG £2SHUDWRU2YHUORDGLQJ0HWKRGV¤RQSDJH  ‡ 6XSHUFODVVHV DOVRNQRZQDVEDVHFODVVHV IURPZKLFKD QHZFODVVLQKHULWVDWWULEXWHVDUHOLVWHGLQSDUHQWKHVHVLQ WKHKHDGHU HJclass Sub(Super1, Super2):  ‡ $VVLJQPHQWVLQWKHVXLWHJHQHUDWHFODVVDWWULEXWHVLQKHUL WHG E\ LQVWDQFHV QHVWHG def VWDWHPHQWV PDNH PHWKRGV ZKLOHDVVLJQPHQWVWDWHPHQWVPDNHVLPSOHFODVVPHPEHUV HWF ‡ &DOOLQJWKHFODVVJHQHUDWHVLQVWDQFHREMHFWV(DFKLQVWDQFH REMHFW PD\ KDYH LWV RZQ DWWULEXWHV DQG LQKHULWV WKH DW WULEXWHVRIWKHFODVVDQGDOORILWVVXSHUFODVVHV ‡ 0HWKRGIXQFWLRQVUHFHLYHDVSHFLDOILUVWDUJXPHQWXVXDOO\ FDOOHGselfZKLFKLVWKHLQVWDQFHREMHFWWKDWLVWKHLPSOLHG VXEMHFWRIWKHPHWKRGFDOODQGJLYHVDFFHVVWRLQVWDQFH VWDWHLQIRUPDWLRQDWWULEXWHV ‡ 6SHFLDOO\QDPHG__X__PHWKRGGHILQLWLRQVLQWHUFHSWEXLOW LQRSHUDWLRQV

Class decorators in Python 2.6 and 3.0 ,Q3\WKRQDQGODWHUGHFRUDWRUV\QWD[FDQEHDSSOLHG WR FODVV VWDWHPHQWV LQ DGGLWLRQ WR IXQFWLRQ GHILQLWLRQV 7KH FODVVGHFRUDWRUV\QWD[ @decorator class C: def meth(): ...

74 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

LVHTXLYDOHQWWRWKLVPDQXDOQDPHUHELQGLQJ class C: def meth(): ... C = decorator(C)

7KHHIIHFWLVWRUHELQGWKHFODVVQDPHWRWKHUHVXOWRISDVVLQJ WKHFODVVWKURXJKWKHGHFRUDWRUFDOODEOH/LNHIXQFWLRQGHFRUD WRUVFODVVGHFRUDWRUVPD\EHQHVWHGDQGVXSSRUWGHFRUDWRUDU JXPHQWV&ODVVGHFRUDWRUVPD\EHXVHGWRPDQDJHFODVVHVRU ODWHU LQVWDQFHFUHDWLRQ FDOOV PDGH WR WKHP E\ XVLQJ SUR[\ REMHFWV 

Metaclasses 0HWDFODVVHVDUHFODVVHVWKDWJHQHUDOO\VXEFODVVIURPWKHW\SH FODVV LQ RUGHU WR FXVWRPL]H FUHDWLRQ RI FODVV REMHFWV WKHPVHOYHV class Meta(type): def __new__(meta, cname, supers, cdict): # run by inherited type.__call__ return type.__new__(meta, cname, supers, cdict)

,Q3\WKRQFODVVHVGHILQHWKHLUPHWDFODVVHVXVLQJNH\ZRUG DUJXPHQWVLQclassKHDGHUV class C(metaclass=Meta): ...

,Q3\WKRQ;XVHFODVVDWWULEXWHVLQVWHDG class C: __metaclass__ = Meta ...

6HH DOVR type() LQ £%XLOWLQ )XQFWLRQV¤ RQ SDJH  IRU WKH PDSSLQJIURPFODVVVWDWHPHQWV

The try Statement try: suite except [type [as value]]: suite [except [type [as value]]:

# [, value] in Python 2

Specific Statements | 75

More free ebooks : http://fast-file.blogspot.com

suite]* [else: suite] [finally: suite] try: suite finally: suite

7KHtryVWDWHPHQWFDWFKHVH[FHSWLRQVtryVWDWHPHQWVFDQVSHF LI\exceptFODXVHVZLWKVXLWHVWKDWVHUYHDVKDQGOHUVIRUH[FHS WLRQV UDLVHG GXULQJ WKH try VXLWH else FODXVHV WKDW UXQ LI QR H[FHSWLRQRFFXUVGXULQJWKHtryVXLWHDQGfinallyFODXVHVWKDW UXQZKHWKHUDQH[FHSWLRQKDSSHQVRUQRWexceptFODXVHVFDWFK DQGUHFRYHUIURPH[FHSWLRQVDQG finallyFODXVHVGHILQHWHU PLQDWLRQDFWLRQV ([FHSWLRQVFDQEHUDLVHGE\3\WKRQRUH[SOLFLWO\ VHHDOVRWKH raiseVWDWHPHQWGLVFXVVHGLQWKHQH[WVHFWLRQ£7KHUDLVH6WDWH PHQW¤ RQ SDJH   ,Q except FODXVHV type LV DQ H[SUHVVLRQ JLYLQJWKHH[FHSWLRQFODVVWREHFDXJKWDQGDQH[WUDYDULDEOH QDPHvalueFDQEHXVHGWRLQWHUFHSWWKHLQVWDQFHRIWKHH[FHS WLRQFODVVWKDWZDVUDLVHG7DEOHOLVWVDOOWKHFODXVHVWKDWFDQ DSSHDULQDtryVWDWHPHQW 7KHtryPXVWKDYHHLWKHUDQexceptRUDfinallyRUERWK7KH RUGHURILWVSDUWVPXVWEH tryൺexceptൺelseൺfinallyZKHUH WKH elseDQG finallyDUHRSWLRQDODQGWKHUHPD\EH]HURRU PRUH exceptEXWWKHUHPXVWEHDWOHDVWRQH exceptLIDQ else DSSHDUV finally LQWHUDFWV FRUUHFWO\ ZLWK return break DQG continue LIDQ\RIWKHVHSDVVFRQWURORXWRIWKHtryEORFNWKH finallyFODXVHLVH[HFXWHGRQWKHZD\RXW  7DEOHWU\VWDWHPHQWFODXVHIRUPDWV Clause format

Interpretation

except:

Catch all (or all other) exceptions

except type:

Catch a specific exception only

76 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Clause format

Interpretation

except type as value:

Catch exception and its instance

except (type1, type2):

Catch any of the exceptions

except (type1, type2) as value:

Catch any of the exceptions and its instance

else:

Run if no exceptions are raised

finally:

Always run this block on the way out

&RPPRQYDULDWLRQVLQFOXGHWKHIROORZLQJ exceptclassnameas X:

&DWFK D FODVV H[FHSWLRQ DQG DVVLJQ X WR WKH UDLVHG LQ VWDQFH X JLYHV DFFHVV WR DQ\ DWWDFKHG VWDWH LQIRUPDWLRQ DWWULEXWHV SULQW VWULQJV RU FDOODEOH PHWKRGV RQ WKH LQ VWDQFHUDLVHG)RUROGHUVWULQJH[FHSWLRQVXLVDVVLJQHGWR WKHH[WUDGDWDSDVVHGDORQJZLWKWKHVWULQJ VWULQJH[FHS WLRQVDUHUHPRYHGLQ3\WKRQDQG  except (type1,type2,type3) asX:

&DWFKDQ\RIWKHH[FHSWLRQVQDPHGLQDWXSOHDQGDVVLJQ XWRWKHH[WUDGDWD 6HH DOVR WKH sys.exc_info() FDOO LQ £7KH V\V 0RG XOH¤RQSDJHIRUJHQHULFDFFHVVWRWKHH[FHSWLRQFODVVDQG LQVWDQFH DNDW\SHDQGYDOXH DIWHUDQH[FHSWLRQLVUDLVHG

Python 2.X try statement forms ,Q3\WKRQ; tryVWDWHPHQWVZRUNDVGHVFULEHGEXWWKH as FODXVHXVHGLQexceptKDQGOHUVWRDFFHVVWKHUDLVHGLQVWDQFHLV FRGHGZLWKDFRPPDLQVWHDG exceptclassname, X:

&DWFK D FODVV H[FHSWLRQ DQG DVVLJQ X WR WKH UDLVHG LQVWDQFH except (name1name2name2),X:

&DWFKDQ\RIWKHH[FHSWLRQVDQGDVVLJQXWRWKHH[WUDGDWD

Specific Statements | 77

More free ebooks : http://fast-file.blogspot.com

The raise Statement ,Q3\WKRQWKHraiseVWDWHPHQWWDNHVWKHIROORZLQJIRUPV raiseinstance[fromotherexc]

5DLVHDPDQXDOO\FUHDWHGLQVWDQFHRIDFODVV HJ raise Error(args)  raiseclass[fromotherexc]

0DNH DQG UDLVH D QHZ LQVWDQFH RI class HTXLYDOHQW WR raiseclass()  raise

5HUDLVHWKHPRVWUHFHQWH[FHSWLRQ 7KH raise VWDWHPHQW WULJJHUV H[FHSWLRQV IRUIXOOEXIIHULQJ%XIIHUHGGDWDWUDQVIHUVPLJKWQRW EHLPPHGLDWHO\IXOILOOHG XVHfile.flushWRIRUFH  encodingLVWKHQDPHRIWKHHQFRGLQJXVHGWRGHFRGHRUHQFRGH

DWH[WILOH¦VFRQWHQWRQWUDQVIHUV7KLVVKRXOGEHXVHGLQWH[W PRGHRQO\7KHGHIDXOWHQFRGLQJLVSODWIRUPGHSHQGHQWEXW DQ\ HQFRGLQJ VXSSRUWHG E\ 3\WKRQ FDQ EH SDVVHG 6HH WKH codecsPRGXOHIRUWKHOLVWRIVXSSRUWHGHQFRGLQJV errorsLVDQRSWLRQDOVWULQJWKDWVSHFLILHVKRZHQFRGLQJHUURUV

DUHWREHKDQGOHG7KLVVKRXOGEHXVHGLQWH[WPRGHRQO\3DVV 'strict'WRUDLVHDValueErrorH[FHSWLRQLIWKHUHLVDQHQFRGLQJ HUURU WKH GHIDXOW RI None KDV WKH VDPH HIIHFW  RU SDVV 'ignore'WRLJQRUHHUURUV,JQRULQJHQFRGLQJHUURUVFDQOHDGWR

಩ ,QIDFWEHFDXVHILOHPRGHLPSOLHVERWKFRQILJXUDWLRQRSWLRQVDQGVWULQJ GDWDW\SHVLW¦VSUREDEO\EHVWWRWKLQNRI open()LQWHUPVRIWZRGLVWLQFW IODYRUV¢WH[WDQGELQDU\DVVSHFLILHGLQWKHPRGHVWULQJ3\WKRQGHYHORSHUV FKRVHWRRYHUORDGDVLQJOHIXQFWLRQWRVXSSRUWWKHWZRILOHW\SHVZLWKPRGH VSHFLILF DUJXPHQWV DQG GLIIHULQJ FRQWHQW W\SHV UDWKHU WKDQ SURYLGH WZR VHSDUDWHRSHQIXQFWLRQVDQGILOHREMHFWW\SHV

112 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

GDWD ORVV 6HH codecs.register() IRU D OLVW RI WKH SHUPLWWHG YDOXHV newlineFRQWUROVKRZXQLYHUVDOQHZOLQHVZRUNDQGDSSOLHVWR WH[WPRGHRQO\,WFDQEHNone WKHGHIDXOW '''\n''\r'DQG '\r\n'

‡ 2QLQSXWLI newlineLV NoneXQLYHUVDOQHZOLQHVPRGHLV HQDEOHGOLQHVPD\HQGLQ '\n' '\r'RU '\r\n'DQGDOO WKHVHDUHWUDQVODWHGWR '\n'EHIRUHEHLQJUHWXUQHGWRWKH FDOOHU,InewlineLV''XQLYHUVDOQHZOLQHPRGHLVHQDEOHG EXWOLQHHQGLQJVDUHUHWXUQHGWRWKHFDOOHUXQWUDQVODWHG,I LWKDVDQ\RIWKHRWKHUOHJDOYDOXHVLQSXWOLQHVDUHRQO\ WHUPLQDWHGE\WKHJLYHQVWULQJDQGWKHOLQHHQGLQJLVUH WXUQHGWRWKHFDOOHUXQWUDQVODWHG ‡ 2QRXWSXWLInewlineLVNoneDQ\'\n'FKDUDFWHUVZULWWHQ DUH WUDQVODWHG WR WKH V\VWHP GHIDXOW OLQH VHSDUDWRU os.linesep,InewlineLV''QRWUDQVODWLRQWDNHVSODFH,I LWLVDQ\RIWKHRWKHUOHJDOYDOXHVDQ\'\n'FKDUDFWHUVZULW WHQDUHWUDQVODWHGWRWKHJLYHQVWULQJ ,I closefdLV FalseWKHXQGHUO\LQJILOHGHVFULSWRUZLOOEHNHSW RSHQZKHQWKHILOHLVFORVHG7KLVGRHVQRWZRUNZKHQDILOH QDPHLVJLYHQDVDVWULQJDQGPXVWEHTrue WKHGHIDXOW LQWKDW FDVH ord(C)

5HWXUQV DQ LQWHJHU FRGHSRLQW YDOXH RI D RQHFKDUDFWHU VWULQJC)RU$6&,,FKDUDFWHUVWKLVLVWKHELW$6&,,FRGH RICIRUZLGHU8QLFRGHWKLVLVWKH8QLFRGHFRGHSRLQWRI DRQHFKDUDFWHU8QLFRGHVWULQJ pow(X, Y [, Z]) 5HWXUQV XWRSRZHU Y>PRGXOR Z@,WLVVLPLODUWRWKH **

H[SUHVVLRQRSHUDWRU print([object,...] [, sep=' '] [, end='n'] [, file=sys.stdout]) 3ULQWVobject V WRWKHVWUHDPfileVHSDUDWHGE\sepDQG IROORZHGE\ end sep endDQG fileLISUHVHQWPXVWEH

JLYHQDVNH\ZRUGDUJXPHQWVDQGGHIDXOWDVVKRZQ Built-in Functions | 113

More free ebooks : http://fast-file.blogspot.com

$OOQRQNH\ZRUGDUJXPHQWVDUHFRQYHUWHGWRVWULQJVOLNH str()GRHVDQGZULWWHQWRWKHVWUHDP%RWK sepDQG end PXVWHLWKHUEHVWULQJVRUNone PHDQLQJXVHWKHLUGHIDXOW YDOXHV ,IQRobjectLVJLYHQendLVZULWWHQfilePXVWEH DQREMHFWZLWKD write(string)PHWKRGEXWQHHGQRWEH DQDFWXDOILOHLILWLVQRWSDVVHGRULVNonesys.stdoutZLOO EHXVHG3ULQWIXQFWLRQDOLW\LVDYDLODEOHDVDVWDWHPHQWIRUP LQ3\WKRQ; VHH£6SHFLILF6WDWHPHQWV¤RQSDJH  property([fget[, fset[, fdel[, doc]]]])

5HWXUQVDSURSHUW\DWWULEXWHIRUQHZVW\OHFODVVHV FODVVHV WKDWGHULYHIURPobject fgetLVDIXQFWLRQIRUJHWWLQJDQ DWWULEXWHYDOXH fsetLVDIXQFWLRQIRUVHWWLQJDQG fdelLV DIXQFWLRQIRUGHOHWLQJ7KLVFDOOPD\EHXVHGDVDIXQFWLRQ GHFRUDWRU LWVHOI DQG UHWXUQV DQ REMHFW ZLWK PHWKRGV getter setterDQG deleterZKLFKPD\DOVREHXVHGDV GHFRUDWRUV LQ WKLV UROH VHH £7KH GHI 6WDWH PHQW¤RQSDJH  range([start,] stop [, step])

5HWXUQVVXFFHVVLYHLQWHJHUVEHWZHHQstartDQGstop:LWK RQH DUJXPHQW LW UHWXUQV LQWHJHUV IURP ]HUR WKURXJK stop-1 :LWK WZR DUJXPHQWV LW UHWXUQV LQWHJHUV IURP start WKURXJK stop-1 :LWK WKUHH DUJXPHQWV LW UHWXUQV LQWHJHUVIURP startWKURXJK stop-1DGGLQJ stepWRHDFK SUHGHFHVVRU LQ WKH UHVXOW start step GHIDXOW WR   range(0, 20, 2)LVDOLVWRIHYHQLQWHJHUVIURPWKURXJK 7KLVFDOOLVRIWHQXVHGWRJHQHUDWHRIIVHWOLVWVRUUHSHDW FRXQWVLQforORRSV ,Q3\WKRQWKLVFDOOUHWXUQVDOLVW,Q3\WKRQLWUH WXUQVDQLWHUDEOHREMHFWWKDWJHQHUDWHVYDOXHVRQGHPDQG DQGFDQEHWUDYHUVHGPXOWLSOHWLPHV ZUDSLQDlist()FDOO WRIRUFHUHVXOWVJHQHUDWLRQLIUHTXLUHG  repr(object)

5HWXUQV D VWULQJ FRQWDLQLQJ D SULQWDEOH DQG SRWHQWLDOO\ SDUVHDEOHDVFRGHUHSUHVHQWDWLRQRIDQ\object,Q3\WKRQ ; EXW QRW 3\WKRQ   WKLV LV HTXLYDOHQW WR `object` EDFNTXRWHVH[SUHVVLRQ 

114 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

reversed(seq)

5HWXUQVDUHYHUVHLWHUDWRUseqPXVWEHDQREMHFWWKDWKDV D __reversed__()PHWKRGRUVXSSRUWVWKHVHTXHQFHSUR WRFRO WKH __len__() PHWKRG DQG WKH __getitem__() PHWKRGZLWKLQWHJHUDUJXPHQWVVWDUWLQJDW  round(X [, N])

5HWXUQVWKHIORDWLQJSRLQWYDOXHXURXQGHGWRNGLJLWVDIWHU WKHGHFLPDOSRLQWNGHIDXOWVWR]HURDQGPD\EHQHJDWLYH WRGHQRWHGLJLWVWRWKHOHIWRIWKHGHFLPDOSRLQW7KHUHWXUQ YDOXHLVDQLQWHJHULIFDOOHGZLWKRQHDUJXPHQWRWKHUZLVH RI WKH VDPH W\SH DV X ,Q 3\WKRQ ; RQO\ WKH UHVXOW LV DOZD\V D IORDWLQJSRLQW ,Q 3\WKRQ  RQO\ FDOOV X.__round__() set([iterable])

5HWXUQV D VHW ZKRVH HOHPHQWV DUH WDNHQ IURP iterable 7KH HOHPHQWV PXVW EH LPPXWDEOH 7R UHSUHVHQW VHWV RI VHWV WKH QHVWHG VHWV VKRXOG EH frozenset REMHFWV ,I iterable LV QRW VSHFLILHG WKLV UHWXUQV D QHZ HPSW\ VHW $YDLODEOH VLQFH YHUVLRQ  6HH DOVR WKH VHFWLRQ £6HWV¤RQSDJHDQGWKH{...}VHWOLWHUDOLQ3\WKRQ setattr(object, name, value) $VVLJQVvalueWRWKHDWWULEXWHname DVWULQJ LQobject/LNH object.name = valueEXW nameLVDUXQWLPHVWULQJQRWD YDULDEOH QDPH WDNHQ OLWHUDOO\ HJ setattr(a,'b',c) LV HTXLYDOHQWWRa.b=c  slice([start ,] stop [, step])

5HWXUQVDVOLFHREMHFWUHSUHVHQWLQJDUDQJHZLWKUHDGRQO\ DWWULEXWHV start stop DQG step DQ\ RI ZKLFK FDQ EH None$UJXPHQWVDUHWKHVDPHDVIRU range6OLFHREMHFWV PD\EHXVHGLQSODFHRIi:j:kVOLFHQRWDWLRQ HJX[i:j] LVHTXLYDOHQWWRX[slice(i, j)]  sorted(iterable, key=None, reverse=False)

5HWXUQVDQHZVRUWHGOLVWIURPWKHLWHPVLQiterable7KH RSWLRQDO NH\ZRUG DUJXPHQWV key DQG reverse KDYH WKH VDPH PHDQLQJ DV WKRVH IRU WKH list.sort() PHWKRG GH VFULEHG HDUOLHU key LV D RQHDUJXPHQW YDOXH WUDQVIRUP IXQFWLRQ7KLVZRUNVRQDQ\LWHUDEOHDQGUHWXUQVDQHZ Built-in Functions | 115

More free ebooks : http://fast-file.blogspot.com

REMHFWLQVWHDGRIFKDQJLQJDOLVWLQSODFHDQGLVWKXVXVHIXO LQ for ORRSV WRDYRLGVSOLWWLQJVRUWFDOOVRXWWRVHSDUDWH VWDWHPHQWVGXHWR NoneUHWXUQV$YDLODEOHLQYHUVLRQ DQGODWHU ,Q 3\WKRQ ; WKLV KDV FDOO VLJQDWXUH sorted(iterable, cmp=None, key=None, reverse=False)ZKHUHRSWLRQDODU JXPHQWVcmpkeyDQGreverseKDYHWKHVDPHPHDQLQJDV WKRVHIRUWKH3\WKRQ; list.sort()PHWKRGGHVFULEHG HDUOLHULQWKLVERRN staticmethod(function)

5HWXUQVDVWDWLFPHWKRGIRUfunction$VWDWLFPHWKRGGRHV QRWUHFHLYHDQLPSOLFLWILUVWDUJXPHQWDQGVRLVXVHIXOIRU SURFHVVLQJ FODVV DWWULEXWHV WKDW VSDQ LQVWDQFHV 8VH WKH @staticmethodIXQFWLRQGHFRUDWRULQYHUVLRQDQGODWHU VHHWKHVHFWLRQ£7KHGHI6WDWHPHQW¤RQSDJH  str([object [, encoding [, errors]]])

5HWXUQVD£XVHUIULHQGO\¤DQGSULQWDEOHVWULQJYHUVLRQRI DQREMHFW7KLVLVDOVRDVXEFODVVDEOHW\SHQDPH2SHUDWHV LQRQHRIWKHIROORZLQJPRGHV ‡ :KHQRQO\objectLVJLYHQWKLVUHWXUQVLWVQLFHO\SULQW DEOHUHSUHVHQWDWLRQ)RUVWULQJVWKLVLVWKHVWULQJLWVHOI 7KHGLIIHUHQFHZLWK repr(object)LVWKDW str(object) GRHVQRWDOZD\VDWWHPSWWRUHWXUQDVWULQJWKDWLVDF FHSWDEOH WR eval() LWV JRDO LV WR UHWXUQ D SULQWDEOH VWULQJ :LWK QR DUJXPHQWV WKLV UHWXUQV WKH HPSW\ VWULQJ ‡ ,IencodingDQGRUerrorsDUHSDVVHGWKLVZLOOGHFRGH WKHREMHFWZKLFKFDQHLWKHUEHDE\WHVWULQJRUDFKDU DFWHU EXIIHU XVLQJ WKH FRGHF IRU encoding 7KH encodingSDUDPHWHULVDVWULQJJLYLQJWKHQDPHRIDQ HQFRGLQJLIWKHHQFRGLQJLVQRWNQRZQLookupErrorLV UDLVHG(UURUKDQGOLQJLVGRQHDFFRUGLQJWR errorsLI HUURUVLV 'strict' WKHGHIDXOW D ValueErrorLVUDLVHG IRUHQFRGLQJHUURUVZKLOHDYDOXHRI 'ignore'FDXVHV HUURUVWREHVLOHQWO\LJQRUHGDQGDYDOXHRI'replace' FDXVHV WKH RIILFLDO 8QLFRGH UHSODFHPHQW FKDUDFWHU U +FFFDWREHXVHGWRUHSODFHLQSXWFKDUDFWHUVWKDWFDQ 116 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

QRWEHGHFRGHG6HHDOVRWKH codecsPRGXOHDQGWKH VLPLODU bytes.decode() PHWKRG b'a\xe4'.decode('latin-1') LV HTXLYDOHQW WR str(b'a\xe4', 'latin-1')  ,Q 3\WKRQ ; WKLV FDOO KDV VLPSOHU VLJQDWXUH str([object])DQGUHWXUQVDVWULQJFRQWDLQLQJWKHSULQW DEOH UHSUHVHQWDWLRQ RI object WKH ILUVW XVDJH PRGH LQ 3\WKRQ  sum(iterable [, start]) 6XPVstartDQGWKHLWHPVRIDQLWHUDEOHIURPOHIWWRULJKW DQGUHWXUQVWKHWRWDO startGHIDXOWVWR7KHLWHUDEOH¦V

LWHPV DUH QRUPDOO\ QXPEHUV DQG DUH QRW DOORZHG WR EH VWULQJV WR FRQFDWHQDWH DQ LWHUDEOH RI VWULQJV XVH ''.join(iterable)  super([type [, object-or-type]]) 5HWXUQVWKHVXSHUFODVVRItype,IWKHVHFRQGDUJXPHQWLV

RPLWWHG WKH VXSHU REMHFW UHWXUQHG LV XQERXQG ,I WKH VHFRQG DUJXPHQW LV DQ REMHFW isinstance(obj, type) PXVW EH WUXH ,I WKH VHFRQG DUJXPHQW LV D W\SH issubclass(type2, type) PXVW EH WUXH &DOOLQJ super() ZLWKRXW DUJXPHQWV LV HTXLYDOHQW WR super(this_class, first_arg) ,Q D VLQJOHLQKHULWDQFH FODVV KLHUDUFK\ WKLV FDOOFDQEHXVHGWRUHIHUWRSDUHQWFODVVHVZLWKRXWQDPLQJ WKHPH[SOLFLWO\7KLVFDOOFDQDOVREHXVHGWRLPSOHPHQW FRRSHUDWLYHPXOWLSOHLQKHULWDQFHLQDG\QDPLFH[HFXWLRQ HQYLURQPHQW 7KLVZRUNVRQO\IRUQHZVW\OHFODVVHVLQ3\WKRQ; ZKHUH typeLVQRWRSWLRQDO DQGIRUDOOFODVVHVLQ3\WKRQ tuple([iterable])

5HWXUQV D QHZ WXSOH ZLWK WKH VDPH HOHPHQWV DV DQ\ iterableSDVVHGLQ,IiterableLVDOUHDG\DWXSOHLWLVUH WXUQHGGLUHFWO\ QRWDFRS\ ,IQRDUJXPHQWUHWXUQVDQHZ HPSW\WXSOH7KLVLVDOVRDVXEFODVVDEOHW\SHFODVVQDPH type(object | (name, bases, dict))

7KLVFDOOLVXVHGLQWZRGLIIHUHQWPRGHVGHWHUPLQHGE\ FDOOSDWWHUQ Built-in Functions | 117

More free ebooks : http://fast-file.blogspot.com

‡ :LWKRQHDUJXPHQWUHWXUQVDW\SHREMHFWUHSUHVHQWLQJ WKHW\SHRI object8VHIXOIRUW\SHWHVWLQJLQ ifVWDWH PHQWV HJ type(X)==type([]) DVZHOODVGLFWLRQDU\ NH\V6HHDOVRPRGXOHtypesIRUSUHVHWW\SHREMHFWVWKDW DUHQRWEXLOWLQQDPHVDQGisinstance()HDUOLHULQWKLV VHFWLRQ 'XH WR WKH UHFHQW PHUJLQJ RI W\SHV DQG FODVVHV type(object) LV JHQHUDOO\ WKH VDPH DV object.__class__ ,Q 3\WKRQ ; WKH types PRGXOH DOVRLQFOXGHVEXLOWLQW\SHV ‡ :LWKWKUHHDUJXPHQWVVHUYHVDVDFRQVWUXFWRUUHWXUQ LQJDQHZW\SHREMHFW7KLVLVDG\QDPLFIRUPRIWKH classVWDWHPHQW7KHnameVWULQJLVWKHFODVVQDPHDQG EHFRPHV WKH __name__ DWWULEXWH WKH bases WXSOH LWHPL]HVWKHEDVHFODVVHVDQGEHFRPHVWKH __bases__ DWWULEXWH DQG WKH dict GLFWLRQDU\ LV WKH QDPHVSDFH FRQWDLQLQJGHILQLWLRQVIRUFODVVERG\DQGEHFRPHVWKH __dict__DWWULEXWHclass X(object): a = 1LVHTXLYD OHQW WR X = type('X', (object,), dict(a=1)) 7KLV PDSSLQJ LV FRPPRQO\ XVHG IRU PHWDFODVV FRQVWUXFWLRQ vars([object])

:LWKRXWDUJXPHQWVUHWXUQVDGLFWLRQDU\FRQWDLQLQJWKH FXUUHQWORFDOVFRSH¦VQDPHV:LWKDPRGXOHFODVVRUFODVV LQVWDQFH REMHFW DV DQ DUJXPHQW LW UHWXUQV D GLFWLRQDU\ FRUUHVSRQGLQJ WR object¦V DWWULEXWH QDPHVSDFH LH LWV __dict__ 7KHUHVXOWVKRXOGQRWEHPRGLILHG8VHIXOIRU %VWULQJIRUPDWWLQJ zip([iterable [, iterable]*])

5HWXUQVDVHULHVRIWXSOHVZKHUHHDFKLWKWXSOHFRQWDLQV WKHLWKHOHPHQWIURPHDFKRIWKHDUJXPHQWLWHUDEOHV)RU H[DPSOH zip('ab', 'cd')UHWXUQV ('a', 'c')DQG ('b', 'd')]$WOHDVWRQHLWHUDEOHLVUHTXLUHGRUD TypeErrorLV UDLVHG7KHUHVXOWVHULHVLVWUXQFDWHGWRWKHOHQJWKRIWKH VKRUWHVW DUJXPHQW LWHUDEOH :LWK D VLQJOH LWHUDEOH DUJX PHQWLWUHWXUQVDVHULHVRIRQHWXSOHV0D\DOVREHXVHG WRXQ]LS]LSSHGWXSOHVX, Y = zip(*zip(T1, T2))

118 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

,Q3\WKRQWKLVUHWXUQVDOLVW,Q3\WKRQLWUHWXUQV DQLWHUDEOHREMHFWWKDWJHQHUDWHVYDOXHVRQGHPDQGDQG FDQEHWUDYHUVHGRQO\RQFH ZUDSLQDlist()FDOOWRIRUFH UHVXOWVJHQHUDWLRQLIUHTXLUHG ,Q3\WKRQ; EXWQRW3\ WKRQ ZKHQWKHUHDUHPXOWLSOHDUJXPHQWLWHUDEOHVRIWKH VDPHOHQJWKzipLVVLPLODUWRmapZLWKDILUVWDUJXPHQWRI None

Python 2.X Built-in Functions 7KHSULRUVHFWLRQ¦VOLVWDSSOLHVWR3\WKRQ6HPDQWLFGLIIHUHQ FHVEHWZHHQEXLOWLQVDYDLODEOHLQERWK3\WKRQDQG;DUH QRWHGLQWKHSULRUVHFWLRQ

Python 3.0 built-ins not supported by Python 2.6 3\WKRQ ; GRHV QRW KDYH WKH IROORZLQJ 3\WKRQ  EXLOWLQ IXQFWLRQV ‡ ascii() WKLVZRUNVOLNH3\WKRQ¦Vrepr() ‡ exec() WKLVLVDVWDWHPHQWIRUPLQ3\WKRQ;ZLWKVLPLODU VHPDQWLFV ‡ memoryview() ‡ print() SUHVHQWLQ3\WKRQ¦V __builtin__PRGXOHEXW QRWGLUHFWO\XVDEOHV\QWDFWLFDOO\DVSULQWLQJLVDVWDWHPHQW IRUPDQGUHVHUYHGZRUGLQ3\WKRQ;

Python 2.6 built-ins not supported by Python 3.0 3\WKRQ ; KDV WKH IROORZLQJ DGGLWLRQDO EXLOWLQ IXQFWLRQV VRPHRIZKLFKDUHDYDLODEOHLQGLIIHUHQWIRUPVLQ3\WKRQ apply(func, pargs [, kargs]) &DOOVDQ\FDOODEOHREMHFWfunc DIXQFWLRQPHWKRGFODVV HWF SDVVLQJWKHSRVLWLRQDODUJXPHQWVLQWXSOHpargsDQG WKHNH\ZRUGDUJXPHQWVLQGLFWLRQDU\kargs,WUHWXUQVWKH funcFDOOUHVXOW

,Q3\WKRQWKLVLVUHPRYHG8VHWKHDUJXPHQWXQSDFN LQJFDOOV\QWD[LQVWHDGfunc(*pargs, **kargs)7KLVIRUP Built-in Functions | 119

More free ebooks : http://fast-file.blogspot.com

LVDOVRSUHIHUUHGLQ3\WKRQDVLWLVPRUHJHQHUDODQG V\PPHWULFZLWKIXQFWLRQGHILQLWLRQV basestring()

7KHEDVHFODVVIRUQRUPDODQG8QLFRGHVWULQJV XVHIXOIRU isinstanceWHVWV  ,Q3\WKRQWKHVLQJOHstrW\SHUHSUHVHQWVDOOWH[W ZLGH 8QLFRGHDQGRWKHU  buffer(object [, offset [, size]])

5HWXUQVDQHZEXIIHUREMHFWIRUDFRQIRUPLQJobject VHH WKH3\WKRQ/LEUDU\5HIHUHQFH  7KLV FDOO LV UHPRYHG LQ 3\WKRQ  7KH QHZ memory view()EXLOWLQSURYLGHVVLPLODUIXQFWLRQDOLW\ callable(object) 5HWXUQV1LIobjectLVFDOODEOHRWKHUZLVHUHWXUQV0

7KLV FDOO LV UHPRYHG LQ 3\WKRQ  8VH hasattr(f, '__call__')LQVWHDG cmp(X, Y)

5HWXUQVDQHJDWLYHLQWHJHU]HURRUDSRVLWLYHLQWHJHUWR GHVLJQDWHX < YX == YRUX > YUHVSHFWLYHO\ ,Q3\WKRQWKLVLVUHPRYHGEXWPD\EHVLPXODWHGDV (X > Y) - (X < Y)+RZHYHUPRVWFRPPRQ cmp()XVH FDVHV FRPSDULVRQ IXQFWLRQV LQ VRUWV DQG WKH __cmp__ PHWKRGRIFODVVHV KDYHDOVREHHQUHPRYHGLQ3\WKRQ coerce(X, Y)

5HWXUQVDWXSOHFRQWDLQLQJWKHWZRQXPHULFDUJXPHQWVX DQGYFRQYHUWHGWRDFRPPRQW\SH 7KLVFDOOLVUHPRYHGLQ3\WKRQ LWVPDLQXVHFDVHZDV IRU3\WKRQ;FODVVLFFODVVHV  execfile(filename [, globals [, locals]]) /LNHevalEXWUXQVDOOWKHFRGHLQDILOHZKRVHVWULQJQDPH LVSDVVHGLQDVfilename LQVWHDGRIDQH[SUHVVLRQ 8QOLNH

LPSRUWVWKLVGRHVQRWFUHDWHDQHZPRGXOHREMHFWIRUWKH ILOH,WUHWXUQVNone1DPHVSDFHVIRUFRGHLQ filenameDUH DVIRUeval

120 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

,Q 3\WKRQ  WKLV PD\ EH VLPXODWHG DV exec(open(filename).read()) file(filename [, mode[, bufsize]]) $QDOLDVIRUWKHopen()EXLOWLQIXQFWLRQDQGWKHVXEFODVV

DEOHFODVVQDPHRIWKHEXLOWLQILOHW\SH ,Q3\WKRQWKHQDPH fileLVUHPRYHGXVH open()WR FUHDWHILOHREMHFWVDQGioPRGXOHFODVVHVWRFXVWRPL]HILOH RSHUDWLRQ input([prompt]) RULJLQDOIRUP 3ULQWVpromptLIJLYHQ7KHQLWUHDGVDQLQSXWOLQHIURPWKH VWGLQVWUHDP sys.stdin HYDOXDWHVLWDV3\WKRQFRGHDQG UHWXUQVWKHUHVXOW,WLVOLNHeval(raw_input(prompt)) ,Q 3\WKRQ  EHFDXVH raw_input() ZDV UHQDPHG input()WKHRULJLQDO3\WKRQ;input()LVQRORQJHUDYDLO DEOHEXWPD\EHVLPXODWHGDVeval(input{prompt)) intern(string) (QWHUVstringLQWKHWDEOHRI£LQWHUQHGVWULQJV¤DQGUHWXUQV

WKHLQWHUQHGVWULQJ,QWHUQHGVWULQJVDUH£LPPRUWDOV¤DQG VHUYH DV D SHUIRUPDQFH RSWLPL]DWLRQ WKH\ FDQ EH FRP SDUHGE\IDVWisLGHQWLW\UDWKHUWKDQ==HTXDOLW\  ,Q3\WKRQWKLVFDOOKDVEHHQPRYHGWR sys.intern() ,PSRUWPRGXOHsysWRXVHLW long(X [, base])

&RQYHUWVDQXPEHURUDVWULQJXWRDORQJLQWHJHUbaseFDQ EHSDVVHGRQO\LIXLVDVWULQJ,IWKHEDVHLVGHWHUPLQHG E\WKHVWULQJFRQWHQWVRWKHUZLVHLWLVXVHGIRUWKHEDVHRI WKHFRQYHUVLRQ,WLVDVXEFODVVDEOHW\SHFODVVQDPH ,Q 3\WKRQ  WKH int LQWHJHU W\SH VXSSRUWV DUELWUDULO\ ORQJSUHFLVLRQDQGVRVXEVXPHV3\WKRQ¦VlongW\SH8VH int()LQ3\WKRQ raw_input([prompt])

7KLVLVWKH3\WKRQ;QDPHRIWKH3\WKRQ input() IXQFWLRQGHVFULEHGLQWKHSULRUVHFWLRQ ,Q3\WKRQXVHWKHinput()EXLOWLQ

Built-in Functions | 121

More free ebooks : http://fast-file.blogspot.com

reduce(func, iterable [, init])

$SSOLHV WKH WZRDUJXPHQW IXQFWLRQ func WR VXFFHVVLYH LWHPVIURP iterableVRDVWRUHGXFHWKHFROOHFWLRQWRD VLQJOHYDOXH,IinitLVJLYHQLWLVSUHSHQGHGWRiterable ,Q 3\WKRQ  WKLV EXLOWLQ LV VWLOO DYDLODEOH DV functools.reduce(),PSRUWPRGXOHfunctoolsWRXVHLW reload(module)

5HORDGVUHSDUVHVDQGUHH[HFXWHVDQDOUHDG\LPSRUWHG moduleLQWKHPRGXOH¦VFXUUHQWQDPHVSDFH5HH[HFXWLRQ UHSODFHVSULRUYDOXHVRIWKHPRGXOH¦VDWWULEXWHVLQSODFH modulePXVWUHIHUHQFHDQH[LVWLQJPRGXOHREMHFWLWLVQRW DQHZQDPHRUDVWULQJ7KLVLVXVHIXOLQLQWHUDFWLYHPRGH LI\RXZDQWWRUHORDGDPRGXOHDIWHUIL[LQJLWZLWKRXWUH VWDUWLQJ3\WKRQ,WUHWXUQVWKHmoduleREMHFW ,Q 3\WKRQ  WKLV EXLOWLQ LV VWLOO DYDLODEOH DV imp.reload(),PSRUWPRGXOHimpWRXVHLW unichr(i)

5HWXUQVWKH8QLFRGHVWULQJRIRQHFKDUDFWHUZKRVH8QL FRGH FRGH LV WKH LQWHJHU i HJ unichr(97) UHWXUQV WKH VWULQJu'a' 7KLVLVWKHLQYHUVHRIordIRU8QLFRGHVWULQJV DQGWKH8QLFRGHYHUVLRQRIchr()7KHDUJXPHQWPXVWEH LQUDQJHLQFOXVLYHRUValueErrorLVUDLVHG ,Q3\WKRQQRUPDOVWULQJVUHSUHVHQW8QLFRGHFKDUDF WHUVXVHWKH chr()FDOOLQVWHDG HJ ord('\xe4')LV 228 DQGchr(228)DQGchr(0xe4)ERWKUHWXUQ'ä'  unicode(string [, encoding [, errors]]) 'HFRGHVstringXVLQJWKHFRGHFIRU encoding(UURUKDQ GOLQJLVGRQHDFFRUGLQJWRerrors7KHGHIDXOWEHKDYLRULV

WRGHFRGH87)LQVWULFWPRGHPHDQLQJWKDWHQFRGLQJ HUURUVUDLVHValueError6HHDOVRWKHcodecsPRGXOHLQWKH 3\WKRQ/LEUDU\5HIHUHQFH ,Q3\WKRQWKHUHLVQRVHSDUDWHW\SHIRU8QLFRGH¢WKH strW\SHUHSUHVHQWVDOOWH[W ZLGH8QLFRGHDQGRWKHU DQG WKHbytesW\SHUHSUHVHQWVELWE\WHELQDU\GDWD8VHQRU PDO str VWULQJV IRU 8QLFRGH WH[W bytes.decode() RU str()WRGHFRGHIURPUDZE\WHVWR8QLFRGHDFFRUGLQJWR 122 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

DQHQFRGLQJDQGQRUPDOILOHREMHFWVWRSURFHVV8QLFRGH WH[WILOHV xrange([start,] stop [, step]) /LNHrangeEXWGRHVQ¦WDFWXDOO\VWRUHWKHHQWLUHOLVWDOODW

RQFH UDWKHULWJHQHUDWHVRQHLQWHJHUDWDWLPH 7KLVLV XVHIXO LQ for ORRSV ZKHQ WKHUH LV D ELJ UDQJH DQG OLWWOH PHPRU\,WRSWLPL]HVVSDFHEXWJHQHUDOO\KDVQRVSHHG EHQHILW ,Q3\WKRQWKHRULJLQDOrange()IXQFWLRQLVFKDQJHGWR UHWXUQ DQ LWHUDEOH LQVWHDG RI SURGXFLQJ D UHVXOW OLVW LQ PHPRU\ DQG WKXV VXEVXPHV 3\WKRQ ¦V xrange() 8VH range()LQ3\WKRQ ,QDGGLWLRQWKHILOHopenFDOOKDVFKDQJHGUDGLFDOO\HQRXJKLQ 3\WKRQ  WKDW LQGLYLGXDO PHQWLRQ RI 3\WKRQ ¦V YDULDQW LV ZDUUDQWHG LQ3\WKRQ;codecs.openKDVPDQ\RIWKHIHDWXUHV LQ3\WKRQ¦Vopen  open(filename [, mode, [bufsize]])

5HWXUQV D QHZ ILOH REMHFW FRQQHFWHG WR WKH H[WHUQDO ILOH QDPHG filename DVWULQJ RUUDLVHV IOErrorLIWKHRSHQ IDLOV7KHILOHQDPHLVPDSSHGWRWKHFXUUHQWZRUNLQJGL UHFWRU\XQOHVVLWLQFOXGHVDGLUHFWRU\SDWKSUHIL[7KHILUVW WZR DUJXPHQWV DUH JHQHUDOO\ WKH VDPH DV WKRVH IRU &¦V fopenIXQFWLRQDQGWKHILOHLVPDQDJHGE\WKH stdioV\V WHP:LWKopen()ILOHGDWDLVDOZD\VUHSUHVHQWHGDVDQRU PDOstrVWULQJLQ\RXUVFULSWFRQWDLQLQJE\WHVIURPWKHILOH codecs.open()LQWHUSUHWVILOHFRQWHQWDVHQFRGHG8QLFRGH WH[WUHSUHVHQWHGDVunicodeREMHFWV  modeGHIDXOWVWR 'r'LIRPLWWHGEXWFDQEH 'r'IRULQSXW 'w'IRURXWSXW WUXQFDWLQJWKHILOHILUVW  'a'IRUDSSHQG DQG 'rb' 'wb'RU 'ab'IRUELQDU\ILOHV WRVXSSUHVVOLQH HQGFRQYHUVLRQVWRDQGIURP\n 2QPRVWV\VWHPVPRVW RIWKHVHFDQDOVRKDYHD+DSSHQGHGWRRSHQLQLQSXWRXW SXWXSGDWHVPRGH HJ 'r+'WRUHDGZULWHDQG 'w+'WR

UHDGZULWHEXWLQLWLDOL]HWKHILOHWRHPSW\  bufsizeGHIDXOWVWRDQLPSOHPHQWDWLRQGHSHQGHQWYDOXH EXWFDQEHIRUXQEXIIHUHGIRUOLQHEXIIHUHGQHJDWLYH Built-in Functions | 123

More free ebooks : http://fast-file.blogspot.com

IRUV\VWHPGHIDXOWRUDJLYHQVSHFLILFVL]H%XIIHUHGGDWD WUDQVIHUV PLJKW QRW EH LPPHGLDWHO\ IXOILOOHG XVH ILOH flushPHWKRGVWRIRUFH 

Built-in Exceptions 7KLVVHFWLRQGHVFULEHVWKHH[FHSWLRQVWKDW3\WKRQPLJKWUDLVH GXULQJDSURJUDP¦VH[HFXWLRQ%HJLQQLQJZLWK3\WKRQDOO EXLOWLQ H[FHSWLRQV DUH FODVV REMHFWV SULRU WR  WKH\ ZHUH VWULQJV %XLOWLQH[FHSWLRQVDUHSURYLGHGLQWKHEXLOWLQVFRSH QDPHVSDFH0DQ\EXLOWLQH[FHSWLRQVKDYHDVVRFLDWHGVWDWHLQ IRUPDWLRQWKDWSURYLGHVH[FHSWLRQGHWDLOV

Superclasses (Categories) 7KH IROORZLQJ H[FHSWLRQV DUH XVHG RQO\ DV VXSHUFODVVHV IRU RWKHUH[FHSWLRQV BaseException

7KH URRW VXSHUFODVV IRU DOO EXLOWLQ H[FHSWLRQV ,W LV QRW PHDQWWREHGLUHFWO\LQKHULWHGE\XVHUGHILQHGFODVVHVXVH ExceptionIRUWKLVUROHLQVWHDG,Istr()LVFDOOHGRQDQLQ VWDQFHRIWKLVFODVVWKHUHSUHVHQWDWLRQRIWKHFRQVWUXFWRU DUJXPHQW V  SDVVHG ZKHQ FUHDWLQJ WKH LQVWDQFH DUH UH WXUQHG RUWKHHPSW\VWULQJLIWKHUHZHUHQRVXFKDUJX PHQWV 7KHVHLQVWDQFHFRQVWUXFWRUDUJXPHQWVDUHVWRUHG DQG PDGH DYDLODEOH LQ WKH LQVWDQFH¦V args DWWULEXWH DV D WXSOH6XEFODVVHVLQKHULWWKLVSURWRFRO Exception

7KHURRWVXSHUFODVVIRUDOOEXLOWLQDQGQRQV\VWHPH[LWLQJ H[FHSWLRQV7KLVLVDGLUHFWVXEFODVVRIBaseException 8VHUGHILQHGH[FHSWLRQVVKRXOGLQKHULW EHGHULYHG IURP WKLVFODVV7KLVGHULYDWLRQLVUHTXLUHGIRUXVHUGHILQHGH[ FHSWLRQVLQ3\WKRQ3\WKRQUHTXLUHVWKLVRIQHZ VW\OHFODVVHVEXWDOVRDOORZVVWDQGDORQHH[FHSWLRQFODVVHV

124 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

tryVWDWHPHQWVWKDWFDWFKWKLVH[FHSWLRQZLOOFDWFKDOOEXW

V\VWHPH[LWHYHQWVEHFDXVHWKLVFODVVLVVXSHUFODVVWRDOO H[FHSWLRQV EXW SystemExit KeyboardInterrupt DQG GeneratorExit WKHVH WKUHH GHULYH GLUHFWO\ IURP BaseExceptionLQVWHDG  ArithmeticError

$ULWKPHWLF HUURU H[FHSWLRQV FDWHJRU\ WKH VXSHUFODVV RI OverflowError ZeroDivisionError DQG FloatingPointErrorDQGDVXEFODVVRIException LookupError

6HTXHQFH DQG PDSSLQJ LQGH[ HUURUV WKH VXSHUFODVV IRU IndexErrorDQGKeyErrorDQGDVXEFODVVRIException EnvironmentError

7KH FDWHJRU\ IRU H[FHSWLRQV WKDW RFFXU RXWVLGH 3\WKRQ WKHVXSHUFODVVIRUIOErrorDQGOSErrorDQGDVXEFODVVRI Exception7KHUDLVHGLQVWDQFHLQFOXGHVLQIRUPDWLRQDODW WULEXWHVerrnoDQGstrerror DQGSRVVLEOHfilenameIRUH[ FHSWLRQVLQYROYLQJILOHSDWKV ZKLFKDUHDOVRLQargs

Specific Exceptions Raised 7KHIROORZLQJFODVVHVDUHH[FHSWLRQVWKDWDUHDFWXDOO\UDLVHG,Q DGGLWLRQ NameError RuntimeError SyntaxError ValueError DQG WarningDUHVSHFLILFH[FHSWLRQVDQGVXSHUFODVVHVWRRWKHU EXLOWLQH[FHSWLRQV AssertionError

5DLVHGZKHQDQassertVWDWHPHQW¦VWHVWLVIDOVH AttributeError

5DLVHGRQDWWULEXWHUHIHUHQFHRUDVVLJQPHQWIDLOXUH EOFError

5DLVHGZKHQWKHLPPHGLDWHHQGRIILOHLVKLWE\ input() RUraw_input()LQ3\WKRQ )LOHUHDGPHWKRGVUHWXUQDQ HPSW\REMHFWDWHQGRIILOHLQVWHDG FloatingPointError

5DLVHGRQIORDWLQJSRLQWRSHUDWLRQIDLOXUH

Built-in Exceptions | 125

More free ebooks : http://fast-file.blogspot.com

GeneratorExit

5DLVHGZKHQDJHQHUDWRU¦Vclose()PHWKRGLVFDOOHG7KLV GLUHFWO\LQKHULWVIURP BaseExceptionLQVWHDGRI Exception VLQFHLWLVQRWDQHUURU IOError

5DLVHGRQ,2RUILOHUHODWHGRSHUDWLRQIDLOXUHV'HULYHG IURP EnvironmentErrorZLWKVWDWHLQIRUPDWLRQGHVFULEHG DERYH ImportError

5DLVHGZKHQDQ importRU fromIDLOVWRILQGDPRGXOHRU DWWULEXWH IndentationError

5DLVHG ZKHQ LPSURSHU LQGHQWDWLRQ LV IRXQG LQ VRXUFH FRGH'HULYHGIURPSyntaxError IndexError

5DLVHGRQRXWRIUDQJHVHTXHQFHRIIVHWV IHWFKRUDVVLJQ  6OLFH LQGH[HV DUH VLOHQWO\ DGMXVWHG WR IDOO LQ WKH DOORZHG UDQJHLIDQLQGH[LVQRWDQLQWHJHUTypeErrorLVUDLVHG KeyError

5DLVHGRQUHIHUHQFHVWRQRQH[LVWHQWPDSSLQJNH\V IHWFK  $VVLJQPHQWWRDQRQH[LVWHQWNH\FUHDWHVWKDWNH\ KeyboardInterrupt

5DLVHGRQXVHUHQWU\RIWKHLQWHUUXSWNH\ QRUPDOO\&WUO &RU'HOHWH 'XULQJH[HFXWLRQDFKHFNIRULQWHUUXSWVLV PDGHUHJXODUO\7KLVH[FHSWLRQLQKHULWVGLUHFWO\IURPBase ExceptionWRSUHYHQWLWIURPEHLQJDFFLGHQWDOO\FDXJKWE\ FRGHWKDWFDWFKHVExceptionDQGWKXVSUHYHQWVLQWHUSUHWHU H[LW MemoryError

5DLVHGRQUHFRYHUDEOHPHPRU\H[KDXVWLRQ7KLVFDXVHVD VWDFNWUDFHWREHGLVSOD\HGLIDUXQDZD\SURJUDPZDVLWV FDXVH NameError

5DLVHG RQ IDLOXUHV WR ILQG D ORFDO RU JOREDO XQTXDOLILHG QDPH

126 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

NotImplementedError

5DLVHGRQIDLOXUHVWRGHILQHH[SHFWHGSURWRFROV$EVWUDFW FODVVPHWKRGVPD\UDLVHWKLVZKHQWKH\UHTXLUHDPHWKRG WREHUHGHILQHG'HULYHGIURP RuntimeError 7KLVLVQRW WREHFRQIXVHGZLWKNotImplementedDVSHFLDOEXLOWLQRE MHFW UHWXUQHG E\ VRPH RSHUDWRURYHUORDGLQJ PHWKRGV ZKHQRSHUDQGW\SHVDUHQRWVXSSRUWHG OSError

5DLVHGRQosPRGXOHHUURUV LWVos.errorH[FHSWLRQ 'H ULYHG IURP EnvironmentError ZLWK VWDWH LQIRUPDWLRQ GHVFULEHGHDUOLHU OverflowError

5DLVHG RQ H[FHVVLYHO\ ODUJH DULWKPHWLF RSHUDWLRQV 7KLV FDQQRWRFFXUIRULQWHJHUVDVWKH\VXSSRUWDUELWUDU\SUHFL VLRQDQGPRVWIORDWLQJSRLQWRSHUDWLRQVDUHQRWFKHFNHG HLWKHU ReferenceError

5DLVHG LQ FRQMXQFWLRQ ZLWK ZHDN UHIHUHQFHV 6HH WKH weakrefPRGXOH RuntimeError

$UDUHO\XVHGFDWFKDOOH[FHSWLRQ StopIteration

5DLVHGRQWKHHQGRIYDOXHVSURJUHVVLRQLQLWHUDWRUREMHFWV 5DLVHGE\WKHnext(X)EXLOWLQDQGX.__next__()PHWKRGV X.next()LQ3\WKRQ  SyntaxError

5DLVHGZKHQSDUVHUVHQFRXQWHUDV\QWD[HUURU7KLVPD\ RFFXU GXULQJ LPSRUW RSHUDWLRQV FDOOV WR eval() DQG exec()DQGZKHQUHDGLQJFRGHLQDWRSOHYHOVFULSWILOHRU VWDQGDUG LQSXW ,QVWDQFHV RI WKLV FODVV KDYH DWWULEXWHV filename lineno offsetDQG textIRUDFFHVVWRGHWDLOV str()RIWKHH[FHSWLRQLQVWDQFHUHWXUQVRQO\WKHPHVVDJH SystemError

5DLVHGRQLQWHUSUHWHULQWHUQDOHUURUVWKDWDUHQRWVHULRXV HQRXJKWRVKXWGRZQ WKHVHVKRXOGEHUHSRUWHG 

Built-in Exceptions | 127

More free ebooks : http://fast-file.blogspot.com

SystemExit

5DLVHGRQDFDOOWRsys.exit(N),IQRWKDQGOHGWKH3\WKRQ LQWHUSUHWHUH[LWVDQGQRVWDFNWUDFHEDFNLVSULQWHG,IWKH SDVVHGYDOXHLVDQLQWHJHULWVSHFLILHVWKHV\VWHPH[LWVWDWXV SDVVHGRQWR&¦VH[LWIXQFWLRQ LILWLVNoneWKHH[LWVWDWXV LV]HURLILWKDVDQRWKHUW\SHWKHREMHFW¦VYDOXHLVSULQWHG DQG WKH H[LW VWDWXV LV RQH 'HULYHG GLUHFWO\ IURP BaseExceptionWRSUHYHQWLWIURPEHLQJDFFLGHQWDOO\FDXJKW E\FRGHWKDWFDWFKHV ExceptionDQGWKXVSUHYHQWVLQWHU SUHWHUH[LW sys.exit()UDLVHVWKLVH[FHSWLRQVRWKDWFOHDQXSKDQGOHUV finallyFODXVHVRI tryVWDWHPHQWV DUHH[HFXWHGDQGVR

WKDWDGHEXJJHUFDQH[HFXWHDVFULSWZLWKRXWORVLQJFRQ WURO 7KH os._exit() IXQFWLRQ H[LWV LPPHGLDWHO\ ZKHQ QHHGHG HJLQWKHFKLOGSURFHVVDIWHUDFDOOWR fork()  $OVRVHHWKHatexitVWDQGDUGOLEUDU\PRGXOHIRUH[LWIXQF WLRQVSHFLILFDWLRQ TabError

5DLVHGZKHQDQLPSURSHUPL[WXUHRIVSDFHVDQGWDEVLV IRXQGLQVRXUFHFRGH'HULYHGIURPIndentationError TypeError

5DLVHGZKHQDQRSHUDWLRQRUIXQFWLRQLVDSSOLHGWRDQRE MHFWRILQDSSURSULDWHW\SH UnboundLocalError

5DLVHGRQUHIHUHQFHVWRORFDOQDPHVWKDWKDYHQRW\HWEHHQ DVVLJQHGDYDOXH'HULYHGIURPNameError UnicodeError

5DLVHGRQ8QLFRGHUHODWHGHQFRGLQJRUGHFRGLQJHUURUV DVXSHUFODVVFDWHJRU\DQGDVXEFODVVRIValueError UnicodeEncodeError UnicodeDecodeError UnicodeTranslateError

5DLVHGRQ8QLFRGHUHODWHGSURFHVVLQJHUURUVVXEFODVVHV RIUnicodeError

128 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

ValueError

5DLVHGZKHQDEXLOWLQRSHUDWLRQRUIXQFWLRQUHFHLYHVDQ DUJXPHQWWKDWKDVWKHFRUUHFWW\SHEXWDQLQDSSURSULDWH YDOXHDQGWKHVLWXDWLRQLVQRWGHVFULEHGE\DPRUHVSHFLILF H[FHSWLRQOLNHIndexError WindowsError

5DLVHGRQ:LQGRZVVSHFLILFHUURUVDVXEFODVVRIOSError ZeroDivisionError

5DLVHGRQGLYLVLRQRUPRGXOXVRSHUDWLRQVZLWKRQWKH ULJKW

Warning Category Exceptions 7KHIROORZLQJH[FHSWLRQVDUHXVHGDVZDUQLQJFDWHJRULHV Warning

7KHVXSHUFODVVIRUDOORIWKHIROORZLQJZDUQLQJFDWHJRULHV LWLVDGLUHFWVXEFODVVRIException UserWarning

:DUQLQJVJHQHUDWHGE\XVHUFRGH DeprecationWarning

:DUQLQJVDERXWGHSUHFDWHGIHDWXUHV PendingDeprecationWarning

:DUQLQJV DERXW IHDWXUHV WKDW ZLOO EH GHSUHFDWHG LQ WKH IXWXUH SyntaxWarning

:DUQLQJVDERXWGXELRXVV\QWD[ RuntimeWarning

:DUQLQJVDERXWGXELRXVUXQWLPHEHKDYLRU FutureWarning

:DUQLQJVDERXWFRQVWUXFWVWKDWZLOOFKDQJHVHPDQWLFDOO\ LQWKHIXWXUH ImportWarning

:DUQLQJVDERXWSUREDEOHPLVWDNHVLQPRGXOHLPSRUWV

Built-in Exceptions | 129

More free ebooks : http://fast-file.blogspot.com

UnicodeWarning

:DUQLQJVUHODWHGWR8QLFRGH BytesWarning

:DUQLQJV UHODWHG WR bytes DQG EXIIHU PHPRU\YLHZ REMHFWV

Warnings Framework :DUQLQJV DUH LVVXHG ZKHQ IXWXUH ODQJXDJH FKDQJHV PLJKW EUHDNH[LVWLQJFRGHLQDIXWXUH3\WKRQUHOHDVH¢DQGLQRWKHU FRQWH[WV:DUQLQJVPD\EHFRQILJXUHGWRSULQWPHVVDJHVUDLVH H[FHSWLRQV RU EH LJQRUHG 7KH ZDUQLQJV IUDPHZRUN FDQ EH XVHGWRLVVXHZDUQLQJVE\FDOOLQJWKHwarnings.warnIXQFWLRQ warnings.warn("feature obsolete", DeprecationWarning)

,QDGGLWLRQ\RXFDQDGGILOWHUVWRGLVDEOHFHUWDLQZDUQLQJV>> import re >>> patt = re.compile('hello[ \t]*(.*)') >>> mobj = patt.match('hello world!') >>> mobj.group(1) 'world!'

The re Pattern-Matching Module | 159

More free ebooks : http://fast-file.blogspot.com

,Q7DEOH&LVDQ\FKDUDFWHU5LVDQ\UHJXODUH[SUHVVLRQIRUP LQWKHOHIWFROXPQRIWKHWDEOHDQGPDQGQDUHLQWHJHUV(DFK IRUPXVXDOO\FRQVXPHVDVPXFKRIWKHVWULQJEHLQJPDWFKHGDV SRVVLEOHH[FHSWIRUWKHQRQJUHHG\IRUPV ZKLFKFRQVXPHDV OLWWOHDVSRVVLEOHDVORQJDVWKHHQWLUHSDWWHUQVWLOOPDWFKHVWKH WDUJHWVWULQJ  7DEOH5HJXODUH[SUHVVLRQSDWWHUQV\QWD[ Form

Description

.

Matches any character (including newline if DOTALL flag is specified).

^

Matches start of string (of every line in MULTILINE mode).

$

Matches end of string (of every line in MULTILINE mode).

C

Any nonspecial character matches itself.

R*

Zero or more occurrences of preceding regular expression R (as many as possible).

R+

One or more occurrences of preceding regular expression R (as many as possible).

R?

Zero or one occurrence of preceding regular expression R.

R{m}

Matches exactly m repetitions of preceding regular expression R.

R{m,n}

Matches from m to n repetitions of preceding regular expression R.

R*?, R+?, R??, R{m,n}?

Same as *, +, and ?, but matches as few characters/times as possible; nongreedy.

[...]

Defines character set; e.g., [a-zA-Z] matches all letters (also see Table 20).

160 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Form

Description

[^...]

Defines complemented character set: matches if character is not in set.

\

Escapes special characters (e.g., *?+|()) and introduces special sequences (see Table 20). Due to Python rules, write as \\ or r'\\'.

\\

Matches a literal \; due to Python string rules, write as \\\\ in pattern, or r'\\'.

\number

Matches the contents of the group of the same number: (.+) \1 matches “42 42”

R|R

Alternative: matches left or right R.

RR

Concatenation: matches both Rs.

(R)

Matches any RE inside (), and delimits a group (retains matched substring).

(?: R)

Same as (R) but doesn’t delimit a group.

(?= R)

Look-ahead assertion: matches if R matches next, but doesn’t consume any of the string (e.g., X (?=Y) matches X if followed by Y).

(?! R)

Negative look-ahead assertion: matches if R doesn’t match next. Negative of (?=R).

(?P R)

Matches any RE inside () and delimits a named group (e.g., r'(?P[a-zA-Z_]\ w*)' defines a group named id).

The re Pattern-Matching Module | 161

More free ebooks : http://fast-file.blogspot.com

Form

Description

(?P=name)

Matches whatever text was matched by the earlier group named name.

(?#...)

A comment; ignored.

(?letter)

letter is one of a, i, L, m, s, x, or u. Set flag (re.A, re.I, re.L, etc.) for entire RE.

(?if', 1, 2.0)) 8 >>> open('data', 'rb').read() b'\x00\x00\x00\x01@\x00\x00\x00' >>> struct.unpack('>if', open('data', 'rb').read()) (1, 2.0)

Python Portable SQL Database API 3\WKRQ¦VSRUWDEOH64/GDWDEDVH$3,SURYLGHVVFULSWSRUWDELOLW\ EHWZHHQGLIIHUHQWYHQGRUVSHFLILF64/GDWDEDVHSDFNDJHV)RU HDFKYHQGRULQVWDOOWKHYHQGRUVSHFLILFH[WHQVLRQPRGXOHEXW ZULWH\RXUVFULSWVDFFRUGLQJWRWKHSRUWDEOHGDWDEDVH$3,>> from sqlite3 import connect >>> conn = connect(r'C:\users\mark\misc\temp.db') >>> curs = conn.cursor() >>> >>> >>> >>>

curs.execute('create table jobs (name, title, pay)') prefix = 'insert into jobs values ' curs.execute(prefix + "('Bob', 'dev', 100)") curs.execute(prefix + "('Sue', 'dev', 120)")

>>> curs.execute("select * from jobs where pay > 100") >>> for (name, title, pay) in curs.fetchall(): ... print(name, title, pay) ... Sue dev 120 >>> curs.execute("select name, pay from jobs").fetchall() [('Bob', 100), ('Sue', 120)] >>> query = "select * from jobs where title = ?" >>> curs.execute(query, ('dev',)).fetchall() [('Bob', 'dev', 100), ('Sue', 'dev', 120)]

Module Interface 7KLVDQGWKHIROORZLQJVHFWLRQVSURYLGHDSDUWLDOOLVWRIH[SRUWV VHHWKHIXOO$3,VSHFLILFDWLRQDWKWWSZZZS\WKRQRUJIRUGH WDLOVRPLWWHGKHUH connect(parameters...)

&RQVWUXFWRUIRUFRQQHFWLRQREMHFWVUHSUHVHQWVDFRQQHF WLRQWRWKHGDWDEDVH3DUDPHWHUVDUHYHQGRUVSHFLILF paramstyle

6WULQJJLYLQJW\SHRISDUDPHWHUPDUNHUIRUPDWWLQJ HJ qmark ?VW\OH  Warning

([FHSWLRQ UDLVHG IRU LPSRUWDQW ZDUQLQJV VXFK DV GDWD WUXQFDWLRQV Error

([FHSWLRQ WKDW LV WKH EDVH FODVV RI DOO RWKHU HUURU H[FHSWLRQV

180 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Connection Objects &RQQHFWLRQREMHFWVUHVSRQGWRWKHIROORZLQJPHWKRGV close()

&ORVHVWKHFRQQHFWLRQQRZ UDWKHUWKDQZKHQ __del__LV FDOOHG  commit()

&RPPLWVDQ\SHQGLQJWUDQVDFWLRQVWRWKHGDWDEDVH rollback()

5ROOVGDWDEDVHEDFNWRWKHVWDUWRIDQ\SHQGLQJWUDQVDF WLRQ FORVLQJ D FRQQHFWLRQ ZLWKRXW FRPPLWWLQJ WKH FKDQJHVILUVWZLOOFDXVHDQLPSOLFLWUROOEDFN cursor()

5HWXUQVDQHZFXUVRUREMHFWIRUVXEPLWWLQJ64/VWULQJV WKURXJKWKHFRQQHFWLRQ

Cursor Objects &XUVRUREMHFWVUHSUHVHQWGDWDEDVHFXUVRUVXVHGWRPDQDJHWKH FRQWH[WRIDIHWFKRSHUDWLRQ description

6HTXHQFH RI VHYHQLWHP VHTXHQFHV HDFK FRQWDLQV LQIRU PDWLRQ GHVFULELQJ RQH UHVXOW FROXPQ (name type_code display_sizeinternal_sizeprecisionscalenull_ok) rowcount

6SHFLILHVWKHQXPEHURIURZVWKDWWKHODVW execute*SUR GXFHG IRU'4/VWDWHPHQWVOLNH select RUDIIHFWHG IRU '0/VWDWHPHQWVOLNHupdateRUinsert  callproc(procname [,parameters])

&DOOVDVWRUHGGDWDEDVHSURFHGXUHZLWKWKHJLYHQQDPH 7KHVHTXHQFHRISDUDPHWHUVPXVWFRQWDLQRQHHQWU\IRU HDFK DUJXPHQW WKDW WKH SURFHGXUH H[SHFWV UHVXOW LV UH WXUQHGDVDPRGLILHGFRS\RIWKHLQSXWV

Python Portable SQL Database API | 181

More free ebooks : http://fast-file.blogspot.com

close()

&ORVHV WKH FXUVRU QRZ UDWKHU WKDQ ZKHQ __del__ LV FDOOHG  execute(operation [,parameters])

3UHSDUHV DQG H[HFXWHV D GDWDEDVH RSHUDWLRQ TXHU\ RU FRPPDQG SDUDPHWHUVFDQEHVSHFLILHGDVDOLVWRIWXSOHV WR LQVHUW PXOWLSOH URZV LQ D VLQJOH RSHUDWLRQ EXW executemanyLVSUHIHUUHG  executemany(operation, seq_of_parameters)

3UHSDUHVDGDWDEDVHRSHUDWLRQ TXHU\RUFRPPDQG DQG H[HFXWHVLWDJDLQVWDOOSDUDPHWHUVHTXHQFHVRUPDSSLQJV LQ VHTXHQFH seq_of_parameters 6LPLODU WR PXOWLSOH executeFDOOV fetchone()

)HWFKHVWKHQH[WURZRIDTXHU\UHVXOWVHWUHWXUQLQJDVLQ JOHVHTXHQFHRUNoneZKHQQRPRUHGDWDLVDYDLODEOH fetchmany([size=cursor.arraysize])

)HWFKHVWKHQH[WVHWRIURZVRIDTXHU\UHVXOWUHWXUQLQJD VHTXHQFH RI VHTXHQFHV HJ D OLVW RI WXSOHV  $Q HPSW\ VHTXHQFHLVUHWXUQHGZKHQQRPRUHURZVDUHDYDLODEOH fetchall()

)HWFKHVDOO UHPDLQLQJ URZVRIDTXHU\UHVXOWUHWXUQLQJ WKHPDVDVHTXHQFHRIVHTXHQFHV HJDOLVWRIWXSOHV 

Type Objects and Constructors Date(year,month,day)

&RQVWUXFWVDQREMHFWKROGLQJDGDWHYDOXH Time(hour,minute,second)

&RQVWUXFWVDQREMHFWKROGLQJDWLPHYDOXH None

64/18//YDOXHVDUHUHSUHVHQWHGE\WKH3\WKRQNoneRQ LQSXWDQGRXWSXW

182 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Python Idioms and Hints 7KLVVHFWLRQOLVWVFRPPRQ3\WKRQFRGLQJWULFNVDQGJHQHUDO XVDJHKLQWV&RQVXOWWKH3\WKRQ/LEUDU\5HIHUHQFHDQG3\WKRQ /DQJXDJH 5HIHUHQFH KWWSZZZS\WKRQRUJGRF  IRU IXUWKHU LQIRUPDWLRQRQWRSLFVPHQWLRQHGKHUH

Core Language Hints ‡ S[:]PDNHVDWRSOHYHO VKDOORZ FRS\RIDQ\VHTXHQFH copy.deepcopy(X) PDNHV IXOO FRSLHV list(L) DQG D.copy()FRS\OLVWVDQGGLFWLRQDULHV ‡ L[:0]=[X,Y,Z]LQVHUWVLWHPVDWIURQWRIOLVWLLQSODFH ‡ L[len(L):]=[X,Y,Z] L.extend([X,Y,Z]) DQG L += [X,Y,Z] DOO LQVHUW PXOWLSOH LWHPV DW WKH HQG RI D OLVW LQSODFH ‡ L.append(X)DQGX=L.pop()FDQEHXVHGWRLPSOHPHQWLQ SODFHVWDFNRSHUDWLRQVZKHUHWKHHQGRIWKHOLVWLVWKHWRS RIWKHVWDFN ‡ 8VHfor key in D.keys():WRLWHUDWHWKURXJKGLFWLRQDULHV RUVLPSO\for key in D:LQYHUVLRQDQGODWHU,Q3\WKRQ WKHVHWZRIRUPVDUHHTXLYDOHQWVLQFHkeysLVDQLWHUDEOH YLHZ ‡ 8VHfor key in sorted(D):WRLWHUDWHRYHUGLFWLRQDU\NH\V LQ VRUWHG IDVKLRQ LQ YHUVLRQ  DQG ODWHU WKH IRUP K=D.keys(); K.sort(); for key in K: DOVR ZRUNV LQ 3\WKRQ;EXWQRW3\WKRQVLQFHkeysUHVXOWVDUHYLHZ REMHFWVQRWOLVWV ‡ X=A or B or NoneDVVLJQVXWRWKHILUVWWUXHREMHFWDPRQJ ADQGBRUNoneLIERWKDUHIDOVH LHRUHPSW\  ‡ X,Y = Y,XVZDSVWKHYDOXHVRIXDQGY ‡ red, green, blue = range(3)DVVLJQVLQWHJHUVHULHV ‡ 8VH try/finallyVWDWHPHQWVWRHQVXUHWKDWDUELWUDU\WHU PLQDWLRQ FRGH LV UXQ HVSHFLDOO\ XVHIXO DURXQG ORFNLQJ FDOOV DFTXLUHEHIRUHWKHtryUHOHDVHLQWKHfinally  Python Idioms and Hints | 183

More free ebooks : http://fast-file.blogspot.com

‡ 8VH with/asVWDWHPHQWVWRJXDUDQWHHWKDWREMHFWVSHFLILF WHUPLQDWLRQFRGHLVUXQIRUREMHFWVWKDWVXSSRUWWKHFRQ WH[W PDQDJHU SURWRFRO HJ ILOH DXWRFORVH WUHDG ORFN DXWRUHOHDVH  ‡ :UDSLWHUDEOHVLQDlist()FDOOWRYLHZDOOWKHLUUHVXOWVLQ WHUDFWLYHO\LQ3\WKRQWKLVLQFOXGHVrange()map()zip() filter()dict.keys()DQGPRUH

Environment Hints ‡ 8VH if __name__ == '__main__':WRDGGVHOIWHVWFRGHRU DFDOOWRDPDLQIXQFWLRQDWWKHERWWRPRIPRGXOHILOHV WUXHRQO\ZKHQILOHLVUXQQRWZKHQLWLVLPSRUWHGDVD OLEUDU\FRPSRQHQW ‡ 7R ORDG ILOH FRQWHQWV LQ D VLQJOH H[SUHVVLRQ XVH data=open('filename').read() ‡ 7R LWHUDWH WKURXJK WH[W ILOHV E\ OLQHV XVH for line in file:LQYHUVLRQDQGODWHU LQROGHUYHUVLRQVXVH for line in file.readlines():  ‡ 7RUHWULHYHFRPPDQGOLQHDUJXPHQWVXVHsys.argv ‡ 7RUHWULHYHVKHOOHQYLURQPHQWVHWWLQJVXVHos.environ ‡ 7KH VWDQGDUG VWUHDPV DUH sys.stdin sys.stdout DQG sys.stderror ‡ 7R UHWXUQ D OLVW RI ILOHV PDWFKLQJ D JLYHQ SDWWHUQ XVH glob.glob('pattern') ‡ 7RUHWXUQDOLVWRIILOHVDQGVXEGLUHFWRULHVRQDSDWKXVH os.listdir('.') ‡ 7RZDONDQHQWLUHWUHHRIGLUHFWRULHVXVHos.walkLQ3\WKRQ DQG os.path.walkLVDOVRDYDLODEOHLQ3\WKRQ RQO\  ‡ 7R UXQ VKHOO FRPPDQGVZLWKLQ3\WKRQVFULSWV\RX FDQ XVH os.system('cmdline') output=os.popen('cmdline', 'r').read()7KHODWWHUIRUPUHDGVWKHVSDZQHGSURJUDP¦V VWDQGDUG RXWSXW DQG PD\ DOVR EH XVHG WR UHDG OLQHE\OLQH 184 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

‡ 2WKHUVWUHDPVRIDVSDZQHGFRPPDQGDUHDYDLODEOHYLD WKH subprocess PRGXOH LQ 3\WKRQ  DQG WKH os.popen2/3/4 FDOOV LQ 3\WKRQ ; RQO\ 7KH os.fork/ os.exec*FDOOVKDYHVLPLODUHIIHFWRQ8QL[OLNHSODWIRUPV ‡ 7RPDNHDILOHDQH[HFXWDEOHVFULSWRQ8QL[OLNHSODWIRUPV DGG D OLQH OLNH #!/usr/bin/env python RU #!/usr/local/ bin/pythonDWWKHWRSDQGJLYHWKHILOHH[HFXWDEOHSHUPLV VLRQVZLWKD chmodFRPPDQG2Q:LQGRZVILOHVFDQEH FOLFNHGDQGUXQGLUHFWO\GXHWRWKHUHJLVWU\ ‡ 7KHdir([object])IXQFWLRQLVXVHIXOIRULQVSHFWLQJDWWULE XWH QDPHVSDFHV print(object.__doc__) RIWHQ JLYHV GRFXPHQWDWLRQ ‡ 7KHhelp([object])IXQFWLRQSURYLGHVLQWHUDFWLYHKHOSIRU PRGXOHVIXQFWLRQVW\SHVDQGPRUHhelp(str)JLYHVKHOS RQ WKH str W\SH help("module") JLYHV KHOS RQ PRGXOHV HYHQ LI WKH\ KDYH QRW \HW EHHQ LPSRUWHG DQG help("topic")JLYHVKHOSRQNH\ZRUGVDQGRWKHUKHOSWRS LFV XVH"topics"IRUDOLVWRIKHOSWRSLFV  ‡ print()DQGinput() NQRZQDVprintDQGraw_input()LQ 3\WKRQ; XVHsys.stdoutDQGsys.stdinVWUHDPVDVVLJQ WR ILOHOLNH REMHFWV WR UHGLUHFW ,2 LQWHUQDOO\ RU XVH WKH print(..., file=F)IRUPLQ3\WKRQ RUWKH print >> F, ...IRUPLQ3\WKRQ; 

Usage Hints ‡ 8VHfrom __future__ importfeaturenameWRHQDEOHH[SHU LPHQWDOODQJXDJHIHDWXUHVWKDWPLJKWEUHDNH[LVWLQJFRGH ‡ ,QWXLWLRQDERXWSHUIRUPDQFHLQ3\WKRQSURJUDPVLVXVX DOO\ZURQJDOZD\VPHDVXUHEHIRUHRSWLPL]LQJRUPLJUDW LQJWR&8VHWKH profileDQG timePRGXOHV DVZHOODV F3URILOHDQGWLPHLW  ‡ 6HHPRGXOHVunittest DND3\8QLW DQGdoctestIRUDX WRPDWHGWHVWLQJWRROVVKLSSHGZLWKWKH3\WKRQVWDQGDUG OLEUDU\unittestLVDFODVVIUDPHZRUNdoctestVFDQVGRF XPHQWDWLRQVWULQJVIRUWHVWVDQGRXWSXWV Python Idioms and Hints | 185

More free ebooks : http://fast-file.blogspot.com

‡ 6HHWKHpydocOLEUDU\PRGXOHDQGVFULSWVKLSSHGZLWK3\ WKRQIRUH[WUDFWLRQDQGGLVSOD\RIGRFXPHQWDWLRQVWULQJV DVVRFLDWHGZLWKPRGXOHVIXQFWLRQVFODVVHVDQGPHWKRGV ‡ 6HH WKH VHFWLRQ £:DUQLQJV )UDPHZRUN¤ RQ SDJH  DV ZHOO DV -W LQ WKH VHFWLRQ £&RPPDQG/LQH 2S WLRQV¤ RQ SDJH  IRU GHWDLOV DERXW WXUQLQJ RII IXWXUHGHSUHFDWLRQZDUQLQJVHPLWWHGE\WKHLQWHUSUHWHU ‡ 6HH'LVWXWLOV3\,QVWDOOHUS\H[HHJJVDQGRWKHUWRROVIRU 3\WKRQSURJUDPGLVWULEXWLRQRSWLRQV ‡ 6HH3\,QVWDOOHUDQGS\H[HIRUWXUQLQJ3\WKRQSURJUDPV LQWRH[HILOHVIRU:LQGRZV ‡ 6HH 1XP3\ 6FL3\ DQG UHODWHG SDFNDJHV IRU H[WHQVLRQV WKDWWXUQ3\WKRQLQWRDQXPHULFVFLHQWLILFSURJUDPPLQJ WRROZLWKYHFWRUREMHFWVHWF ‡ 6HH =2'% DQG RWKHUV IRU IXOOIHDWXUHG 22'% VXSSRUW WKDWDOORZV3\WKRQQDWLYHREMHFWVWREHVWRUHGE\NH\DQG 64/2EMHFW64/$OFKHP\DQGRWKHUVIRUREMHFWUHODWLRQDO PDSSHUV WKDW DOORZ FODVVHV WR EH XVHG ZLWK UHODWLRQDO WDEOHV ‡ 6HH6:,* DPRQJRWKHUV IRUDWRROWKDWFDQDXWRPDWLFDOO\ JHQHUDWHJOXHFRGHIRUXVLQJ&DQG&OLEUDULHVZLWKLQ 3\WKRQVFULSWV ‡ 6HH,'/(IRUDGHYHORSPHQW*8,VKLSSHGZLWK3\WKRQ ZLWKV\QWD[FRORULQJWH[WHGLWRUVREMHFWEURZVHUVGHEXJ JLQJ HWF VHH DOVR 3\WKRQ:LQ .RPRGR (FOLSVH 1HW%HDQVDQGRWKHUVIRUDGGLWLRQDO,'(RSWLRQV ‡ 6HH (PDFV KHOS IRU WLSV RQ HGLWLQJUXQQLQJ FRGH LQ WKH (PDFVWH[WHGLWRU0RVWRWKHUHGLWRUVVXSSRUW3\WKRQDV ZHOO HJDXWRLQGHQWLQJFRORULQJ LQFOXGLQJ9,0DQG ,'/(VHHWKHHGLWRUV¦SDJHDWZZZS\WKRQRUJ ‡ 3RUWLQJWR3\WKRQXVHWKH−3FRPPDQGOLQHRSWLRQLQ 3\WKRQWRLVVXHLQFRPSDWLELOLW\ZDUQLQJVDQGVHHWKH WRVFULSWZKLFKDXWRPDWLFDOO\FRQYHUWVPXFK;FRGH WRUXQXQGHU;3\WKRQ

186 | Python Pocket Reference

More free ebooks : http://fast-file.blogspot.com

Assorted Hints ‡ ,PSRUWDQWZHEVLWHVWRUHIHUWR KWWSZZZS\WKRQRUJ 7KH3\WKRQKRPHSDJH KWWSRUHLOO\FRP 7KHSXEOLVKHU¦VKRPHSDJH KWWSZZZS\WKRQRUJS\SL $GGLWLRQDOWKLUGSDUW\3\WKRQWRROV KWWSZZZUPLQHWaOXW] 7KHDXWKRU¦VVLWH ‡ 3\WKRQSKLORVRSK\import this ‡
Python Pocket Reference 4th Edition Book

Related documents

210 Pages • 22,067 Words • PDF • 1.3 MB

80 Pages • 18,003 Words • PDF • 519.3 KB

280 Pages • 80,371 Words • PDF • 2.2 MB

410 Pages • 98,897 Words • PDF • 2.1 MB

3 Pages • 652 Words • PDF • 7.6 MB

1,352 Pages • 305,899 Words • PDF • 11 MB

72 Pages • 26,627 Words • PDF • 6.6 MB

20 Pages • 4,558 Words • PDF • 627.7 KB

576 Pages • 158 Words • PDF • 60.7 MB

962 Pages • 266,995 Words • PDF • 18 MB