实例介绍
This is a book about software engineering principles applied to Python. There are many books about software engineering, and many resources available with information about Python. The intersection of those two sets, though, is something that requires action, and that's the gap this book tries to b
Clean Code in Python Copyright o 2018 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information Commissioning Editor: Merint Mathew Acquisition Editor: Denim Pinto Content Development editor: Priyanka Sawant Technical Editor: Gaurav gala Copy Editor: Safis Editing Project Coordinator: Vaidehi Sawant Proofreader: Safis Editing Indexer: Rekha nair Graphics: Jason monteiro Production Coordinator: Shantanu Zagade First published August 2018 Production reference: 1270818 Published by Packt Publishing Ltd Iver 35 Livery street Birmingham B 3 2PB, UK ISBN978-1-78883-583-1 www.packtpub.com To my family and friends, for their unconditional love and support Mariano anaya Mapt mapt.lO Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website Why subscribe? Spend less time learning and more time coding with practical ebooks and videos from over 4, 000 industry professionals Improve your learning with Skill Plans built especially for you Get a free ebook or video every month e mapt is fully searchable Copy and paste, print, and bookmark content PacktPub, com Did you know that Packt offers eBook versions of every book published, with PDF and epubfilesavailableYoucanupgradetotheebookversionatwww.Packtpub.comandasa print book customer, you are entitled to a discount on the e book copy. Get in touch with us at servicegpacktpub com for more details Atwww.packtpub.comyoucanalsoreadacollectionoffreetechnicalarticlessignupfora range of free newsletters and receive exclusive discounts and offers on packt books and eBookS Contributors About the author Mariano anaya is a software engineer who spends most of his time creating software with Python and mentoring fellow programmers. Mariano's main areas of interests besides Python are software architecture functional programming distributed systems and speaking at conferences He was a speaker at euro python 2016 and 2017. to know more about him, you can refer to his github account with the username mariano His speakerdeck username is mariano About the reviewer Nimesh Kiran Verma has a dual degree in maths and computing from Iit delhi and has worked with companies such as linkedIn pavtm and icici for about 5 vears in software development and data science He co-founded a micro-lending company, Upwards Fintech and presently serves as its CTO. He loves coding and has mastery in Python and its popular frameworks, Django and Flask He extensively leverages Amazon Web Services, design patterns, SQL and NOSQL databases to build reliable, scalable and low latency architectures To my mom, Nutan Kiran Verma, who made me what I am today and gave the confidence to pursue all my dreams. Thanks Papa, Naveen, and Prabhat, who motivated me to steal time for this book when in fact i was supposed to be spending it with them. ulhas and the entire Packt team's support was tremendous. Thanks varsha Shetty for introducing me to Packt Packt is searching for authors like you IfyoureinterestedinbecominganauthorforPackt,pleasevisitauthorspacktpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for or submit your own idea Table of contents Preface Chapter 1: Introduction, Code Formatting and tools The meaning of clean code The importance of having clean code The role of code formatting in clean code 889 Adhering to a coding style guide on your project 10 Docstrings and annotations 12 Docstrings 13 Annotations Do annotations replace docstrings? Configuring the tools for enforcing basic quality gates 20 Type hinting with Mypy 20 Checking the code with pylint 21 Setup for automatic checks 21 Summary 24 Chapter 2 Pythonic code 25 Indexes and slices 26 Creating your own sequences 28 Context managers 29 mplementing context managers 32 Properties, attributes, and different types of methods for objects 35 Underscores in Python 35 Properties 38 Iterable objects 40 Creating iterable objects 40 Creating sequences 43 Container objects 45 Dynamic attributes for objects 46 Callable objects Summary of magic methods 49 Caveats in Python 49 Mutable default arguments 50 Extending built-in types 51 Summary 53 References 53 Chapter 3: General Traits of good code 55 Design by contract Table of contents reconditions 58 Postconditions 59 Pythonic contracts 59 Design by contract-conclusions 59 Defensive programming 60 Error handling Value substitution 66 EXception handling 62 Handle exceptions at the right level of abstraction 64 Do not expose tracebacks Avoid empty except blocks 67 Include the original exception 68 Using assertions in Python 69 Separation of concerns 70 Cohesion and coupling Acronyms to live by 77 DRY/OAOO 72 YAGN 74 KIS 74 EAFP/LBYL 76 Composition and inheritance 77 When inheritance is a good decision 78 Anti-patterns for inheritance 79 Multiple inheritance in Python 82 Method Resolution Order(MRO) 82 Mixins 84 Arguments in functions and methods 85 How function arguments work in Python 85 How arguments are copied to functions 86 Variable number of arguments 87 The number of arguments in functions 91 Function arguments and coupling 91 Compact function signatures that take too many arguments 92 Final remarks on good practices for software design 93 Orthogonality in software 94 Structuring the code 95 Summary References 97 Chapter 4: The SOLID Principles 99 Single responsibility principle Q a class with too many responsibilities 100 Distributing responsibilities 102 The open/closed principle 103 Example of maintainability perils for not following the open/closed principle103 Refactoring the events system for extensibility 105 Extending the events system 107 Table of contents Final thoughts about the ocP 109 Liskov's substitution principle 110 Detecting LsP issues with tools 111 Detecting incorrect datatypes in method signatures with Mypy Detecting incompatible signatures with Pylint 113 More subtle cases of l sp violations 113 Remarks on the lsP 116 Interface segregation 117 An interface that provides too much 118 The smaller the interface the better 118 How small should an interface be? 119 Dependency inversion 119 A case of rigid dependencies 120 nverting the dependencies 121 Summary 122 References 123 Chapter 5: Using Decorators to Improve Our Code 124 What are decorators in Python? 124 Decorate functions 126 Decorate classes 127 Other types of decorator 131 Passing arguments to decorators 131 Decorators with nested functions 132 Decorator objects 134 Good uses for decorators 135 Transforming parameters 135 Tracing code 136 Effective decorators-avoiding common mistakes 136 Preserving data about the original wrapped object 136 Dealing with side-effects in decorators 139 Incorrect handling of side-effects in a decorator 139 Requiring decorators with side-effects 141 Creating decorators that will always work 143 The DRY principle with decorators 146 Decorators and separation of concerns 147 Analyzing good decorators 149 Summary 150 References 151 Chapter 6: Getting More Out of Our Objects with Descriptors 152 A first look at descriptors 152 The machinery behind descriptors 153 Exploring each method of the descriptor protocol 156 get (self, instance, owner) 156 set (self, instance, value) 157 【实例截图】
【核心代码】
标签:
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论