Book Image

Mastering Python

By : Rick van Hattem
Book Image

Mastering Python

By: Rick van Hattem

Overview of this book

Python is a dynamic programming language. It is known for its high readability and hence it is often the first language learned by new programmers. Python being multi-paradigm, it can be used to achieve the same thing in different ways and it is compatible across different platforms. Even if you find writing Python code easy, writing code that is efficient, easy to maintain, and reuse is not so straightforward. This book is an authoritative guide that will help you learn new advanced methods in a clear and contextualised way. It starts off by creating a project-specific environment using venv, introducing you to different Pythonic syntax and common pitfalls before moving on to cover the functional features in Python. It covers how to create different decorators, generators, and metaclasses. It also introduces you to functools.wraps and coroutines and how they work. Later on you will learn to use asyncio module for asynchronous clients and servers. You will also get familiar with different testing systems such as py.test, doctest, and unittest, and debugging tools such as Python debugger and faulthandler. You will learn to optimize application performance so that it works efficiently across multiple machines and Python versions. Finally, it will teach you how to access C functions with a simple Python call. By the end of the book, you will be able to write more advanced scripts and take on bigger challenges.
Table of Contents (22 chapters)
Mastering Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
6
Generators and Coroutines – Infinity, One Step at a Time
Index

Preface

Python is a language that is easy to learn and both powerful and convenient from the start. Mastering Python, however, is a completely different question.

Every programming problem you will encounter has at least several possible solutions and/or paradigms to apply within the vast possibilities of Python. This book will not only illustrate a range of different and new techniques but also explain where and when a method should be applied.

This book is not a beginner's guide to Python 3. It is a book that can teach you about the more advanced techniques possible within Python. Specifically targeting Python 3.5 and up, it also demonstrates several Python 3.5-only features such as async def and await statements.

As a Python programmer with many years of experience, I will attempt to rationalize the choices made in this book with relevant background information. These rationalizations are in no way strict guidelines, however. Several of these cases boil down to personal style in the end. Just know that they stem from experience and are, in many cases, the solutions recommended by the Python community.

Some of the references in this book might not be obvious to you if you are not a fan of Monty Python. This book extensively uses spam and eggs instead of foo and bar in code samples. To provide some background information, I recommend watching the "Spam" sketch by Monty Python. It is positively silly!

What this book covers

Chapter 1, Getting Started – One Environment per Project, introduces virtual Python environments using virtualenv or venv to isolate the packages in your Python projects.

Chapter 2, Pythonic Syntax, Common Pitfalls, and Style Guide, explains what Pythonic code is and how to write code that is Pythonic and adheres to the Python philosophy.

Chapter 3, Containers and Collections – Storing Data the Right Way, is where we use the many containers and collections bundled with Python to create code that is fast and readable.

Chapter 4, Functional Programming – Readability Versus Brevity, covers functional programming techniques such as list/dict/set comprehensions and lambda statements that are available in Python. Additionally, it illustrates their similarities with the mathematical principles involved.

Chapter 5, Decorators – Enabling Code Reuse by Decorating, explains not only how to create your own function/class decorators, but also how internal decorators such as property, staticmethod, and classmethod work.

Chapter 6, Generators and Coroutines – Infinity, One Step at a Time, shows how generators and coroutines can be used to lazily evaluate structures of infinite size.

Chapter 7, Async IO – Multithreading without Threads, demonstrates the usage of asynchronous functions using async def and await so that external resources no longer stall your Python processes.

Chapter 8, Metaclasses – Making Classes (Not Instances) Smarter, goes deeper into the creation of classes and how class behavior can be completely modified.

Chapter 9, Documentation – How to Use Sphinx and reStructuredText, shows how you can make Sphinx automatically document your code with very little effort. Additionally, it shows how the Napoleon syntax can be used to document function arguments in a way that is legible both in the code and the documentation.

Chapter 10, Testing and Logging – Preparing for Bugs, explains how code can be tested and how logging can be added to enable easy debugging in case bugs occur at a later time.

Chapter 11, Debugging – Solving the Bugs, demonstrates several methods of hunting down bugs with the use of tracing, logging, and interactive debugging.

Chapter 12, Performance – Tracking and Reducing Your Memory and CPU Usage, shows several methods of measuring and improving CPU and memory usage.

Chapter 13, Multiprocessing – When a Single CPU Core Is Not Enough, illustrates that the multiprocessing library can be used to execute your code, not just on multiple processors but even on multiple machines.

Chapter 14, Extensions in C/C++, System Calls, and C/C++ Libraries, covers the calling of C/C++ functions for both interoperability and performance using Ctypes, CFFI, and native C/C++.

Chapter 15, Packaging – Creating Your Own Libraries or Applications, demonstrates the usage of setuptools and setup.py to build and deploy packages on the Python Package Index (PyPI).

What you need for this book

The only hard requirement for this book is a Python interpreter. A Python 3.5 or newer interpreter is recommended, but many of the code examples will function in older Python versions, such as 2.7, with a simple from __future__ import print_statement added at the top of the file.

Additionally, Chapter 14, Extensions in C/C++, System Calls, and C/C++ Libraries requires a C/C++ compiler, such as GCC, Visual Studio, or XCode. A Linux machine is by far the easiest to execute the C/C++ examples, but these should function on Windows and OS X machines without too much effort as well.

Who this book is for

If you are beyond the absolute Python beginner level, then this book is for you. Even if you are already an expert Python programmer, I guarantee that you will find some useful techniques and insights in this book.

At the very least, it will allow Python 2 programmers to learn a lot more about the new features introduced in Python 3, and specifically Python 3.5.

Basic proficiency in Python is required as the installation of Python interpreters and the basic Python syntax are not covered.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "It should be noted that the type() function has another use as well."

A block of code is set as follows:

import abc
import importlib


class Plugins(abc.ABCMeta):
    plugins = dict()

    def __new__(metaclass, name, bases, namespace):
        cls = abc.ABCMeta.__new__(
            metaclass, name, bases, namespace)

Any command-line input or output is written as follows where the >>> indicate the Python console and the # indicates a regular Linux/Unix shell:

>>> class Spam(object):
…     eggs = 'my eggs'

>>> Spam = type('Spam', (object,), dict(eggs='my eggs'))

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Also, the code for the book is hosted on GitHub at https://github.com/mastering-python/code

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.