Mastering Python
eBook - ePub

Mastering Python

Rick van Hattem

Share book
  1. 486 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Mastering Python

Rick van Hattem

Book details
Book preview
Table of contents
Citations

About This Book

Master the art of writing beautiful and powerful Python by using all of the features that Python 3.5 offers

About This Book

  • Become familiar with the most important and advanced parts of the Python code style
  • Learn the trickier aspects of Python and put it in a structured context for deeper understanding of the language
  • Offers an expert's-eye overview of how these advanced tasks fit together in Python as a whole along with practical examples

Who This Book Is For

Almost anyone can learn to write working script and create high quality code but they might lack a structured understanding of what it means to be 'Pythonic'. If you are a Python programmer who wants to code efficiently by getting the syntax and usage of a few intricate Python techniques exactly right, this book is for you.

What You Will Learn

  • Create a virtualenv and start a new project
  • Understand how and when to use the functional programming paradigm
  • Get familiar with the different ways the decorators can be written in
  • Understand the power of generators and coroutines without digressing into lambda calculus
  • Create metaclasses and how it makes working with Python far easier
  • Generate HTML documentation out of documents and code using Sphinx
  • Learn how to track and optimize application performance, both memory and cpu
  • Use the multiprocessing library, not just locally but also across multiple machines
  • Get a basic understanding of packaging and creating your own libraries/applications

In Detail

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.

Style and Approach

This book is a comprehensive guide that covers advanced features of the Python language, and communicate them with an authoritative understanding of the underlying rationale for how, when, and why to use them.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on β€œCancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Mastering Python an online PDF/ePUB?
Yes, you can access Mastering Python by Rick van Hattem in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Python. We have over one million books available in our catalogue for you to explore.

Information

Year
2016
ISBN
9781785289729
Edition
1

Mastering Python


Table of Contents

Mastering Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started – One Environment per Project
Creating a virtual Python environment using venv
Creating your first venv
venv arguments
Differences between virtualenv and venv
Bootstrapping pip using ensurepip
ensurepip usage
Manual pip install
Installing C/C++ packages
Debian and Ubuntu
Red Hat, CentOS, and Fedora
OS X
Windows
Summary
2. Pythonic Syntax, Common Pitfalls, and Style Guide
Code style – or what is Pythonic code?
Formatting strings – printf-style or str.format?
PEP20, the Zen of Python
Beautiful is better than ugly
Explicit is better than implicit
Simple is better than complex
Flat is better than nested
Sparse is better than dense
Readability counts
Practicality beats purity
Errors should never pass silently
In the face of ambiguity, refuse the temptation to guess
One obvious way to do it
Now is better than never
Hard to explain, easy to explain
Namespaces are one honking great idea
Conclusion
Explaining PEP8
Duck typing
Differences between value and identity comparisons
Loops
Maximum line length
Verifying code quality, pep8, pyflakes, and more
flake8
Pep8
pyflakes
McCabe
flake8
Pylint
Common pitfalls
Scope matters!
Function arguments
Class properties
Modifying variables in the global scope
Overwriting and/or creating extra built-ins
Modifying while iterating
Catching exceptions – differences between Python 2 and 3
Late binding – be careful with closures
Circular imports
Import collisions
Summary
3. Containers and Collections – Storing Data the Right Way
Time complexity – the big O notation
Core collections
list – a mutable list of items
dict – unsorted but a fast map of items
set – like a dict without values
tuple – the immutable list
Advanced collections
ChainMap – the list of dictionaries
counter – keeping track of the most occurring elements
deque – the double ended queue
defaultdict – dictionary with a default value
namedtuple – tuples with field names
enum – a group of constants
OrderedDict – a dictionary where the insertion order matters
heapq – the ordered list
bisect – the sorted list
Summary
4. Functional Programming – Readability Versus Brevity
Functional programming
list comprehensions
dict comprehensions
set comprehensions
lambda functions
The Y combinator
functools
partial – no need to repeat all arguments every time
reduce – combining pairs into a single result
Implementing a factorial function
Processing trees
itertools
accumulate – reduce with intermediate results
chain – combining multiple results
combinations – combinatorics in Python
permutations – combinations where the order matters
compress – selecting items using a list of Booleans
dropwhile/takewhile – selecting items using a function
count – infinite range with decimal steps
groupby – grouping your sorted iterable
islice – slicing any iterable
Summary
5. Decorators – Enabling Code Reuse by Decorating
Decorating functions
Why functools.wraps is important
How are decorators useful?
Memoization using decorators
Decorators with (optional) arguments
Creating decorators using classes
Decorating class functions
Skipping the instance – classmethod and staticmethod
Properties – smart descriptor usage
Decorating classes
Singletons – classes with a single instance
Total ordering – sortable classes the easy way
Useful decorators
Single dispatch – polymorphism in Python
Contextmanager, with statements made easy
Validation, type checks, and conversions
Useless warnings – how to ignore them
Summary
6. Generators and Coroutines – Infinity, One Step at a Time
What are generators?
Advantages and disadvantages of generators
Pipelines – an effective use of generators
tee – using an output multiple times
Generating from generators
Context managers
Coroutines
A basic example
Priming
Closing and throwing exceptions
Bidirectional pipelines
Using the state
Summary
7. Async IO – Multithreading without Threads
Introducing the asyncio library
The async and await statements
Python 3.4
Python 3.5
Choosing between the 3.4 and 3.5 syntax
A simple example of single-threaded parallel processing
Concepts of asyncio
Futures and tasks
Event loops
Event loop implementations
Event loop policies
Event loop usage
Processes
Asynchronous servers and clients
Basic echo server
Summary
8. Metaclasses – Making Classes (Not Instances) Smarter
Dynamically creating classes
A basic metaclass
Arguments to metaclasses
Accessing metaclass attributes through classes
Abstract classes using collections.abc
Internal workings of the abstract classes
Custom type checks
Using abc.ABC before Python 3.4
Automatically registering a plugin system
Importing plugins on-demand
Importing plugins through configuration
Importing plugins through the file system
Order of operations when instantiating classes
Finding the metaclass
Preparing the nam...

Table of contents