1、Python 2 and 3 CompatibilityWith Six and Python-Future LibrariesJoannah NanjekyePython 2 and 3 CompatibilityWith Six and Python-Future LibrariesJoannah NanjekyePython 2 and 3 Compatibility Joannah Nanjekye Kampala, Uganda ISBN-13 (pbk): 978-1-4842-2954-5 ISBN-13 (electronic): 978-1-4842-2955-2https:
2、/doi.org/10.1007/978-1-4842-2955-2Library of Congress Control Number: 2017962338Copyright 2017 by Joannah NanjekyeThis work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, r
3、euse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.Trademarked names, logos
4、, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.The use
5、in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.While the advice and information in this book are believed to be true
6、and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.Cover image designed by
7、FreepikManaging Director: Welmoed SpahrEditorial Director: Todd GreenAcquisitions Editor: Todd GreenDevelopment Editor: James MarkhamTechnical Reviewer: Benjamin PetersonCoordinating Editor: Jill BalzanoCopy Editor: Kim Burton-WeismanCompositor: SPi GlobalIndexer: SPi GlobalArtist: SPi GlobalDistrib
8、uted to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-nyspringer-, or visit . Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Busi
9、ness Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.For information on translations, please e-mail , or visit http:/ Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. F
10、or more information, reference our Print and eBook Bulk Sales web page at http:/ source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the books product page, located at For more detailed information, please visit http:/ on acid-free
11、paperTo my family, who have always given me the support to soar; most importantly, my mother, who always reminds me that one of the best decisions I have ever made was to become an engineer. I am grateful for the all-around support (Internet, food, and everything I cant list here because of space).T
12、o the hardworking chief forensic accountant without a CPA, Edmond Mabinda, who tracks every penny in Ugandaother than his own. Thanks for your work on this and the work you will continue doing.Im not forgetting Phionah Bugosi, the programmer who cares more about the color of her laptop bag than her
13、code. Thanks for your work reviewing all the code.vContentsAbout the Author xiiiAbout the Technical Reviewer xvAcknowledgments xviiIntroduction xix Chapter 1: Printing and Backtick repr 1Print 1Using _future_ 1Using six 2Task: Introducing Your Mentor 3Using _future_ 4Using six 5Backtick repr 6Coexis
14、tence Gotchas 8Summary 8 Chapter 2: Numbers 11Inspecting Integers 11Using Python-futures builtins Module 11Using pastbuiltins from Python-future 12Using six 12Long Integers 12Using Python-futures builtins Module 12欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍! ContentsviFloor Divisio
15、n 13Float Division 13Python 2 Compatible Division (Old Division) 13Octal Constants 16Using _future_ 16Using six 17Summary 18 Chapter 3: Setting Metaclasses 21Metaclasses at a Glance 21Metaclasses: The Python 2 Way 22Metaclasses in Python 3 22Metaclasses Compatibility 23Using Python-future 23Using si
16、x 24Using the with_metaclass() Method 24Using the add_metaclass() Class Decorator 25Summary 27 Chapter 4: Strings and Bytes 31Text and Binary Data 31Unicode String Literals 32Explicit Marking with Prefix 32Import unicode_literals from _future_ 33six to Classify the Unicode Data 33Byte String Literal
17、s 33Explicit Marking with a Prefix 34six to Classify the Binary Data 34Iterating Byte Strings 34Indexing Binary Data 34Looping Binary Data 35Using Python-futures builtins Module 36欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍! ContentsviiUsing chr() and encode() 36Six Byte Iteration
18、37Base Strings 37Python-futures pastbuiltins Module 38six: string_types Constant 39Check against str in the builtins Module 39StringIO 40Optional Import of the Modules 40StringIO from the six Module 41StringIO from the six Module from Python-future 41BytesIO 42BytesIO from the six Module 42BytesIO f
19、rom the six Module Through Python-future 42Summary 43 Chapter 5: Package Imports 47Python Imports 47Regular Imports 47Using from 48Local Imports 48Optional Imports 49Relative Imports 49Compatibility for Renamed Modules 50Compatibility for Relative Imports 51Relative Path Import Syntax 51Summary 51 C
20、hapter 6: Exceptions 53Raising Exceptions 53Raising Exceptions Without a Traceback 53Raising Exceptions with a Traceback 54欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍! ContentsviiiCatching Exceptions 55Exception Chaining 55Using Python-future 56Summary 57 Chapter 7: HTML Processing
21、 59HTML Escaping 59The html Module 59HTML Parsing 60Using Python-future 61Using HTMLParser from htmlparser 61Using HTMLParser from futuremoveshtmlparser 61Using six 62Summary 62 Chapter 8: Working with Files 65File Processing 65ioopen() 66Specifying Encoding on Opening the File 66Specifying Encoding
22、 on Decode 67Python 3 open() builtin 67Summary 68 Chapter 9: Custom Behavior of Classes 69Custom Iterators 69Subclass Object from futures builtins Module 70The implements_iterator Decorator from future 71Iterator Class and Advanced_iterator() from six 72Custom _str_ Methods 73Exercise 72 75Exercise
23、73 76欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍! Contentsixfuture: Python_2_unicode_compatible Decorator 76Exercise 74 76six: Python_2_unicode_compatible Decorator 77Exercise 75 77Custom Boolean Methods 78Using Python-future 78Summary 79 Chapter 10: Collections and Iterators 81Ite
24、rable Dictionary Members 81Keys 81Values 82Items 83Dictionary Members as Lists 84Keys 84Values 85Items 86map88imap 90Range 92Using Python-future 93Using six 93Summary 93 Chapter 11: More Built-ins 95Reduce 95raw_input and input 96Using Python-future 97using six 98exec() 98execfile() 100Using Python-
25、future 100欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍! ContentsxUnichr() 101Using Python-future 101Using six 101Intern() 102Using Python-future 103Using six 104apply 104Using Python-future 105chr() 105Using Python-future 106Using six 106cmp() 107Using Python-future 107reload() 107S
26、ummary 108 Chapter 12: Standard Library Modules 111Tkinter 111Using Python-future 112Using six 113Configparser 113Using configparser Backport 114Using sixmoves 114Queue 114Using Python-future 115Using six 115socketserver 115Using Python-future 117Using six 117欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免
27、费提供500+本Py t h o n 书籍! Contentsxidbm Modules 118Using Python-future 118Using six 119http Module 119Using Python-future 120Using six 120XML-RPC 120ifilterfalse 121Using six 121Using future 121izip_longest 121Using six 121Using future 122UserDict, UserList and UserString 122Using six 122Using future 1
28、23Copy_reg 123Using six 123Using future 123Summary 124Index 127欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍!xiiiAbout the AuthorJoannah Nanjekye is from Uganda. She is a software engineer, a conference speaker, and an open source contributor. She has spoken at PyCon ZA in South Afri
29、ca in 2016 and 2017, and at other Python meetups. She shares her implementation knowledge of Python 2 and 3 support from experiences with open source projects. She worked as a software developer for Laboremus Uganda and Fintech Uganda before pursuing a career as an aeronautical engineer with a focus
30、 on avionics at Kenya Aeronautical College. She is a proud alum of Outreachy and Rails Girls Summer of Code, where she learned most of the engineering skills. She is also proud of her working with qutebrowser and Ceph.欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍!xvAbout the Technica
31、l ReviewerBenjamin Peterson is a core developer of CPython and PyPy. He wrote the six Python 2&3 compatibility library.欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍!xviiAcknowledgmentsWriting a technical book comes later on in ones career. I therefore admit that I have learned from a
32、 lot of experiences. I am sharing a subset of these experiences in this book.First, I would like to thank Wilson Kigundu for the email that always keeps me hoping for a brighter future in my engineering career, sent at a time when my first strike into engineering felt like a blander of the century a
33、t the time.I share content drawing from my experiences as an open source contributor, and as such, I would love to thank the open source mentors that I have worked with on qutebrowser and Ceph. I thank Florian Bruhin for all the guidance he accorded when I worked with Keziah on qutebrowser during Ra
34、ils Girls Summer of Code. Most of the Python and Git that I know, I learned from working on qutebrowser. I also thank Ali Maredia, a mentor from Ceph that sacrificed his time, especially his lunch time, to mentor me on object storage, Ceph, and working with Amazon Web Services during my outreachy in
35、ternship. I am very proud of my work and what I learned during this internship.I also take this opportunity to thank the editors I worked with on my end, but also on the Apress side. Thank you Sandra Nabwire, Lynn Kirabo for your editorial work. Special thanks to the technical editors Ed Schofield (
36、on my end) and Benjamin Peterson (from Apress) for the guidance. Great thanks to Jill Balzano and James Markham for making this book more than a success.Lastly, I would love to thank Paul Bagyenda, my first university programming lecturer that taught me a lesson in persistence. Your Python programmi
37、ng class was one of the hardest, but looking back, I think you taught real programming. If anything, you made me who I am today. You had to appear in my first book.欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍!xixIntroductionAll of our Python eggs supported in a unified code basketPy
38、thon 2 and 3 compatibility has been discussed in many Python gatherings, especially as we approach the Python 2 End Of Life (EOL). It is much more than a topic making news in the community.The Python project started in 1980 as a work by the “Benevolent Dictator For Life” Guido Van Rossum, who contin
39、ues to be commander-in-chief in terms of giving direction to the Python language. In October 2000, Python 2.0 was released with many prime features; its implementation became public and community backed. In December 2008, a backward-incompatible Python 3 (a.k.a. Python 3K and Python 3000) was releas
40、ed; after rigorous testing, it was backported in the backward-compatible Python 2.6.x and Python 2.7.x versions.Python 3 was built to improve significant design shortcomings in the language. There are features in which improvements did not play well with backward compatibility, and therefore needed
41、a new major version number. It removed feature duplication in duplicative constructs and modules while still providing for a multiparadigm language in ways that are more obvious than they were in Python 2.x. It is very accurate to say that you are better off using and supporting Python 3.To assume t
42、hat all Python users will immediately switch to Python 3 is not very wise, however, even though the Python 2 EOL date was postponed to 2020. Despite some discomfort in the Python community, Python 2.7 will be supported for some time. It is clear that Python 3 is the future.We have a future that is p
43、urely Python 3 and a present with Python 2 still in use; therefore, current support for both versions is the best remedyespecially for developers building libraries and tools, and anyone building a system that depends on Python.Much like going on a diet, the transition is not fun, however beneficial
44、 it may be. There is a large contrast when you know you have to do something in which the process is sacrificial but the end justifies the means. The only question asked is whether you would rather stay where you are or persevere your way to a better place.Python 3.0 broke compatibility and a sizabl
45、e portion of Python 2 code does not run in Python 3 unless it is converted. Some people looked at Python 3 as the blander of the Century. Changes to Pythons dynamic typing and the semantics in methods for dictionaries make the translation from Python 2.x to Python 3.x very difficult.2to3 is one of t
46、he quick fixes to translate Python 2 code to Python 3; however, it is not a recommended practice. The clean and tested way is to write a single code base that is capable of running reliably in both Python 2 and 3, using compatibility modules such as Python-future and six. The following are some of t
47、he reasons why you want to support both Python 2 and Python 3:The upcoming Python 2 EOL. The exact date has not been determined, but rumor has it that it will be in 2020 around time for Pycon in the US. You do not want to be caught unaware.Perhaps you have Python 2 users using your system or library
48、, but you want to prepare for the future, which is evidently Python 3. The only option you have is to ensure that your system or library executes reliably in both versions.Youre not ready to entirely port to Python 3. Always choose neutral compatibility. It is the safest.This book unfolds the concep
49、ts you need to know to achieve Python 2 and 3 compatibility.欢迎加入非盈利Py t h o n 编程学习交流QQ群783462347,群里免费提供500+本Py t h o n 书籍! IntroduCtIonxxAbout this BookThis book explains the magic of Python 2 and Python 3 compatibility in a unified code base in 12 detailed chapters. You will work on tasks with an open source mentor (who I will introduce later):Printing is the most known difference between Python 2 and 3. Chapter 1 explains how to write the print statement as a functioninstead with the helper modulesto achieve neutral compatibility. Backtick repr is also discussed.There is also contrast with