Nicht aus der Schweiz? Besuchen Sie lehmanns.de
Clean Python -  Sunil Kapil

Clean Python (eBook)

Elegant Coding in Python

(Autor)

eBook Download: PDF
2019 | 1. Auflage
XV, 274 Seiten
Apress (Verlag)
978-1-4842-4878-2 (ISBN)
Systemvoraussetzungen
46,99 inkl. MwSt
(CHF 45,90)
Der eBook-Verkauf erfolgt durch die Lehmanns Media GmbH (Berlin) zum Preis in Euro inkl. MwSt.
  • Download sofort lieferbar
  • Zahlungsarten anzeigen

Discover the right way to code in Python. This book provides the tips and techniques you need to produce cleaner, error-free, and eloquent Python projects.

Your journey to better code starts with understanding the importance of formatting and documenting your code for maximum readability, utilizing built-in data structures and Python dictionary for improved maintainability, and working with modules and meta-classes to effectively organize your code. You will then dive deep into the new features of the Python language and learn how to effectively utilize them. Next, you will decode key concepts such as asynchronous programming, Python data types, type hinting, and path handling. Learn tips to debug and conduct unit and integration tests in your Python code to ensure your code is ready for production. The final leg of your learning journey equips you with essential tools for version management, managing live code, and intelligent code completion.

After reading and using this book, you will be proficient in writing clean Python code and successfully apply these principles to your own Python projects. 


What You'll Learn

  • Use the right expressions and statements in your Python code 
  • Create and assess Python Dictionary 
  • Work with advanced data structures in Python 
  • Write better modules, classes, functions, and metaclasses
  • Start writing asynchronous Python immediately
  • Discover new features in Python

  

Who This Book Is For

Readers with a basic Python programming knowledge who want to improve their Python programming skills by learning right way to code in Python. 



Sunil Kapil has been in the software profession for the last ten years, writing production code in Python and several other languages. He has worked as a software engineer primarily on back-end services for web and mobile. He has developed, deployed, and maintained small to big projects in production that are being loved and used by millions of users. He has completed these projects with small to big teams in different professional environments for very well-known software companies around the world. He is also a passionate advocate of open source and continuously contributes to projects such as Zulip Chat and Black. He also works with non-profit organizations and contributes to their software projects on a volunteer basis.


Discover the right way to code in Python. This book provides the tips and techniques you need to produce cleaner, error-free, and eloquent Python projects. Your journey to better code starts with understanding the importance of formatting and documenting your code for maximum readability, utilizing built-in data structures and Python dictionary for improved maintainability, and working with modules and meta-classes to effectively organize your code. You will then dive deep into the new features of the Python language and learn how to effectively utilize them. Next, you will decode key concepts such as asynchronous programming, Python data types, type hinting, and path handling. Learn tips to debug and conduct unit and integration tests in your Python code to ensure your code is ready for production. The final leg of your learning journey equips you with essential tools for version management, managing live code, and intelligent code completion.After reading and using this book, you will be proficient in writing clean Python code and successfully apply these principles to your own Python projects.  What You ll LearnUse the right expressions and statements in your Python code Create and assess Python Dictionary Work with advanced data structures in Python Write better modules, classes, functions, and metaclassesStart writing asynchronous Python immediatelyDiscover new features in Python  Who This Book Is ForReaders with a basic Python programming knowledge who want to improve their Python programming skills by learning right way to code in Python. 

Table of Contents 4
About the Author 10
About the Technical Reviewer 11
Acknowledgments 12
Introduction 13
Chapter 1: Pythonic Thinking 14
Write Pythonic Code 15
Naming 15
Variables and Functions 15
Classes 18
Constants 18
Function and Method Arguments 18
Expressions and Statements in Your Code 19
Embrace the Pythonic Way to Write Code 22
Prefer join Instead of In-Place String Concatenation 23
Consider Using is and is not Whenever You Need to Compare with None 23
Prefer Using is not Instead of not … is 24
Consider Using a Function Instead of a Lambda When Binding to an Identifier 24
Be Consistent with the return Statement 25
Prefer Using ““.startswith() and ””.endswith() 26
Use the isinstance() Method Instead of type() for Comparison 27
Pythonic Way to Compare Boolean Values 27
Write Explicit Code for Context Manager 27
Use Linting Tools to Improve Python Code 29
Using Docstrings 31
Module-Level Docstrings 34
Make the Class Docstring Descriptive 36
Function Docstrings 37
Some Useful Docstring Tools 38
Write Pythonic Control Structures 39
Use List Comprehensions 39
Don’t Make Complex List Comprehension 41
Should You Use a Lambda? 43
When to Use Generators vs. List Comprehension 44
Why Not to Use else with Loops 45
Why range Is Better in Python 3 48
Raising Exceptions 50
Frequently Raised Exceptions 50
Leverage finally to Handle Exceptions 52
Create Your Own Exception Class 54
Handle Only Specific Exceptions 56
Watch Out for Third-Party Exceptions 58
Prefer to Have Minimum Code Under try 59
Summary 61
Chapter 2: Data Structures 62
Common Data Structures 62
Use Sets for Speed 63
Use namedtuple for Returning and Accessing Data 65
Access the Data 65
Return the Data 66
Understanding str, Unicode, and byte 68
Use Lists Carefully and Prefer Generators 70
Use zip to Process a List 73
Take Advantage of Python’s Built-in Functions 75
collections 75
csv 75
datetime and time 75
math 75
re 76
tempfile 76
itertools 76
functools 76
sys and os 76
subprocess 77
logging 77
json 77
pickle 77
__future__ 77
Take Advantage of Dictionary 78
When to Use a Dictionary vs. Other Data Structures 78
collections 79
Counter 79
deque 80
defaultdict 81
namedtuple 82
ordereddict 82
Ordered Dictionary vs. Default Dictionary vs. Normal Dictionary 83
switch Statement Using Dictionary 85
Ways to Merge Two Dictionaries 86
Pretty Printing a Dictionary 87
Summary 88
Chapter 3: Writing Better Functions and Classes 89
Functions 89
Create Small Functions 90
Return Generators 92
Raise Exceptions Instead of Returning None 94
Add Behavior Using the default and keyword Arguments 97
Do Not Return None Explicitly 98
Be Defensive While Writing a Function 101
Logging 101
Unit Test 103
Use a Lambda as a Single Expression 104
Classes 106
Right Size of Class? 106
Class Structure 107
Class Variables 109
__init__ 109
Special Python Methods 110
Class Methods 110
Static Methods 110
Instance Methods 110
Private Methods 111
Right Ways to Use @property 111
When to Use Static Methods? 114
Use Abstract Class Inheritance the Pythonic Way 116
Use @classmethod to Access Class State 118
Use the public Attribute Instead of private 119
Summary 121
Chapter 4: Working with Modules and Metaclasses 122
Modules and Metaclasses 122
How Modules Can Help to Organize Code 124
Take Advantage of the __init__ File 127
Import Functions and Classes from Modules in the Right Way 130
Use __all__ to Prevent Imports 132
When to Use Metaclasses 134
Use __new__ for Validating Subclasses 135
Why __slots__ Are Useful 138
Change Class Behavior Using Metaclasses 141
Learn About Python Descriptors 145
Summary 147
Chapter 5: Decorators and Context Managers 149
Decorators 150
What Are Decorators, and Why Are They Useful? 150
Understanding Decorators 151
Modify Behavior Using Decorators 154
Using Multiple Decorators 157
Decorators Accept Arguments 158
Consider Using a Library for Decorators 159
Class Decorators for Maintaining State and Validating Parameters 162
Context Manager 165
Context Managers and Their Usefulness 165
Understanding Context Managers 167
Using contextlib to Build a Context Manager 170
Some Practical Examples of Using a Context Manager 171
Accessing a Database 171
Writing Tests 172
Shared Resource 173
Remote Connection 174
Summary 175
Chapter 6: Generators and Iterators 176
Take Advantage of Iterators and Generators 176
Understanding Iterators 176
What Are Generators? 179
When to Use Iterators 180
Using itertools 183
combinations() 183
permuations() 183
product() 184
count() 184
groupby() 185
Why Generators Are Useful 185
List Comprehension vs. Iterators 186
Take Advantage of the yield Keyword 186
yield from 188
yield Is Faster Compared to a Data Structure 189
Summary 189
Chapter 7: Utilize New Python Features 190
Asynchronous Programming 191
Introducing async in Python 192
How It Works 196
Coroutine Function 197
Coroutine Object 197
asyncio.run() 197
await 197
Tasks 201
Awaitable Objects 203
Coroutines 203
Tasks 205
Futures 206
Timeouts 208
Async Generators 209
Async Comprehensions 210
Async Iterators 211
Third-Party Libraries to Consider for Async Code 214
Curio 214
Trio 216
Typing in Python 219
Types in Python 220
typing Module 221
Union 221
Any 222
Tuple 222
TypeVar and Generics 223
Optional 223
Do Data Types Slow Code? 224
How Typing Helps to Write Better Code 224
Typing Pitfalls 225
super() Method 226
Type Hinting 226
Better Path Handling Using pathlib 227
print() Is a Function Now 227
f-string 227
Keyword Only Arguments 228
Preserving the Order of a Dictionary 229
Iterable Unpacking 229
Summary 229
Chapter 8: Debugging and  Testing Python Code 230
Debugging 231
Debugging Tools 231
pdb 231
ipdb 232
pudb 233
breakpoint 236
Use the Logging Module Instead of print in Production Code 236
Classes and Functions in Logging 238
Use the metrics Library for Identifying Bottlenecks 243
How IPython Is Helpful 244
Testing 247
Why Testing Is Important 247
Pytest vs. UnitTest 248
Property Testing 253
How to Create a Report for Testing 254
Automate Unit Tests 255
Getting Your Code Ready for Production 256
Run Unit and Integration Tests in Python 256
Use Linting to Make Code Consistent 257
flake8 258
pylint 258
Use Code Coverage to Check for Tests 258
Use virtualenv for Your Project 259
Summary 260
Appendix: Some Awesome Python Tools 261
Sphinx 261
Coverage 263
pre-commit 264
Pyenv for virtualenv 265
Jupyter Lab 265
Pycharm/VSCode/Sublime 266
Flake8/Pylint 266
Index 268

Erscheint lt. Verlag 21.5.2019
Zusatzinfo XV, 267 p. 2 illus.
Sprache englisch
Themenwelt Informatik Programmiersprachen / -werkzeuge Python
Informatik Theorie / Studium Compilerbau
Schlagworte Class • clean • Code • Debugging • decorators • dictionary • eloquent • Functions • generators • modules • pep8 • Python • Strings • Testing
ISBN-10 1-4842-4878-3 / 1484248783
ISBN-13 978-1-4842-4878-2 / 9781484248782
Haben Sie eine Frage zum Produkt?
PDFPDF (Wasserzeichen)
Größe: 2,3 MB

DRM: Digitales Wasserzeichen
Dieses eBook enthält ein digitales Wasser­zeichen und ist damit für Sie persona­lisiert. Bei einer missbräuch­lichen Weiter­gabe des eBooks an Dritte ist eine Rück­ver­folgung an die Quelle möglich.

Dateiformat: PDF (Portable Document Format)
Mit einem festen Seiten­layout eignet sich die PDF besonders für Fach­bücher mit Spalten, Tabellen und Abbild­ungen. Eine PDF kann auf fast allen Geräten ange­zeigt werden, ist aber für kleine Displays (Smart­phone, eReader) nur einge­schränkt geeignet.

Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen dafür einen PDF-Viewer - z.B. den Adobe Reader oder Adobe Digital Editions.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen dafür einen PDF-Viewer - z.B. die kostenlose Adobe Digital Editions-App.

Zusätzliches Feature: Online Lesen
Dieses eBook können Sie zusätzlich zum Download auch online im Webbrowser lesen.

Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.

Mehr entdecken
aus dem Bereich
Arbeiten mit NumPy, Matplotlib und Pandas

von Bernd Klein

eBook Download (2023)
Carl Hanser Verlag GmbH & Co. KG
CHF 29,30
Arbeiten mit NumPy, Matplotlib und Pandas

von Bernd Klein

eBook Download (2023)
Carl Hanser Verlag GmbH & Co. KG
CHF 29,30