Index

Symbols

%r, for printable strings, 203

%s, for human-readable strings, 202

* operator, liability of, 4445

* symbol, for keyword-only arguments, 5253

*args

optional keyword arguments and, 48

variable positional arguments and, 4345

**kwargs, for keyword-only arguments, 5354

A

__all__ special attribute

avoiding, 183

listing all public names, 181183

ALL_CAPS format, 3

Allocation of memory, tracemalloc module and, 214216

APIs (application programming interfaces)

future-proofing, 186187

internal, allowing subclass access to, 8082

packages providing stable, 181184

root exceptions and, 184186

using functions for, 6164

append method, 3637

Arguments

defensively iterating over, 3842

keyword, 4548

keyword-only, 5154

optional positional, 4345

as clauses, in renaming modules, 181

as targets, with statements and, 155156

assertEqual helper method, verifying equality, 206

assertRaises helper method, verifying exceptions, 206

assertTrue helper method, for Boolean expressions, 206

asyncio built-in module, vs. blocking I/O, 125

AttributeError exception raising, 102103

Attribute(s). See also Private attributes; Public attributes

adding missing default values, 159160

lazily loading/saving, 100105

metaclasses annotating, 112115

names, conflicts over, 8182

B

Binary mode, for reading/writing data, 7

Binary tree class, inheriting from collections.abc, 8486

bisect module, for binary searches, 169

Blocking operations, in Queue class, 132136

Bookkeeping

with dictionaries, 5558

helper classes for, 5860

bt command, of interactive debugger, 208

Buffer sizes, in Queue class, 132136

Bytecode, interpreter state for, 122

bytes instances, for character sequences, 57

C

__call__ special method, with instances, 6364

callable built-in function, 63

CapitalizedWord format, 3

Central processing unit. See CPU (central processing unit)

C-extension modules

for CPU bottlenecks, 145

problems with, 146

chain function, of itertools module, 170

Child classes, initializing parent classes from, 6973

Child processes, subprocess managing, 118121

Circular dependencies

dynamic imports resolving, 191192

import reordering for, 189190

import/configure/run steps for, 190191

in importing modules, 187188

refactoring code for, 189

Clarity, with keyword arguments, 5154

Class interfaces

@property method improving, 9194

use public attributes for defining, 8788

class statements, metaclasses receiving, 106107

__class__ variable

registering classes and, 108112

super built_in function with, 73

Classes. See also Metaclasses; Subclasses

annotating properties of, 112115

for bookkeeping, 5860

docstrings for, 177

initializing parent, 6973

metaclasses registering, 108112

mix-in, 7378

versioning, 160161

@classmethod

in accessing private attributes, 7879

polymorphism, for constructing objects generically, 6769

Closures, interacting with variable scope, 3136

collections module

defaultdict class from, 168

deque class from, 166167

OrderedDict class from, 167168

collections.abc module, custom containers inheriting from, 8486

combination function, of itertools module, 170

Command-lines

correct Python version, 1, 2

starting child processes, 119120

communicate method

reading child process output, 118119

timeout parameter with, 121

Community-built modules, Python Package Index for, 173174

Complex expressions, helper functions and, 810

Concurrency

coroutines and, 137138

defined, 117

in pipelines, 129132

Queue class and, 132136

concurrent.futures built-in module, enabling parallelism, 146148

configparser built-in module, for production configuration, 201

Containers

inheriting from collections.abc, 8486

iterable, 4142

contextlib built-in module, enabling with statements, 154155

contextmanager decorator

purpose of, 154

as targets and, 155156

continue command, of interactive debugger, 209

Conway’s Game of Life, coroutines and, 138143

Coordinated Universal Time (UTC), in time conversions, 162165

copyreg built-in module

adding missing attribute values, 159160

controlling pickle behavior, 158

providing stable import paths, 161162

versioning classes with, 160161

Coroutines

in Conway’s Game of Life, 138143

purpose of, 137138

in Python 2, 143145

count method, for custom container types, 8586

cProfile module, for accurate profiling, 210213

CPU (central processing unit)

bottleneck difficulties, 145146

time, threads wasting, 131132

usage, child processes and, 118121

CPython interpreter, effect of GIL on, 122123

CPython runtime

memory management with, 214

cumtime column, in profiler statistics, 211

cumtime percall column, in profiler statistics, 211

cycle function, of itertools module, 170

D

Data models, @property improving, 9195

Data races, Lock preventing, 126129

datetime built-in module, for time conversions, 164166

deactivate command, disabling pyvenv tool, 195196

Deadlocks, timeout parameter avoiding, 121

Deallocation of memory, tracemalloc managing, 214216

Debuggers, decorator problems with, 151, 153

Debugging

interactive, with pdb module, 208209

memory usage, 214216

print function and, 202

repr strings for, 202204

root exceptions for, 185186

Decimal class, for numerical precision, 171173

Decorators, functionality of, 151153

functools, 151153

Default arguments

approach to serialization, 159160

namedtuple classes and, 59

using dynamic values for, 4851

Default value hooks, 6264

defaultdict using, 6264

Default values

copyreg built-in module and, 159160

of keyword arguments, 4647

defaultdict class, for dictionaries, 168

Dependencies

circular, 187192

reproducing, 196197

transitive, 192194

Dependency injection, 191

Deployment environments, module-scoped code for, 199201

deque class, as double-ended queue, 166167

Descriptors

enabling reusable property logic, 90

in modifying class properties, 112115

for reusable @property methods, 97100

Deserializing objects

default attribute values and, 159160

pickle built-in module for, 157158

stable import paths and, 161162

Development environment, unique configurations/assumptions for, 199201

Diamond inheritance, initializing parent classes and, 7071

__dict__ attribute, viewing object internals, 204

Dictionaries

bookkeeping with, 5558

comprehension expressions in, 16

default, 168

ordered, 167168

translating related objects into, 7475

__doc__ special attribute, retrieving docstrings, 175176

Docstrings

class-level, 177

documenting default behavior in, 4851

for functions, 178179

importance/placement of, 175176

module, 176177

doctest built-in module, 179

Documentation

docstrings for. See Docstrings

importance of, 175

Documentation-generation tools, 176

Double-ended queues, deque classes as, 166167

__double_leading_underscore format, 3

down command, of interactive debugger, 209

dropwhile function, of itertools module, 170

Dynamic imports

avoiding, 192

resolving circular dependencies, 191192

Dynamic state, defined, 55

E

else blocks

after for/while loops, 2325

during exception handling, 2627

end indexes, in slicing sequences, 1013

__enter__ method, in defining new classes, 154

enumerate built-in function, preferred features of, 2021

environ dictionary, tailoring modules with, 201

eval built-in function, for re-creating original values, 203

Exceptions

raising, 2931

root, 184187

try/finally blocks and, 2628

Execution time, optimization of, 209213

__exit__ method, in defining new classes, 154

Expressions

in list comprehensions, 1618

PEP 8 guidance for, 4

F

filter built-in function, list comprehensions vs., 1516

filterfalse function, of itertools module, 170

finally blocks, during exception handling, 2627

First-in-first-out queues, deque class for, 166167

for loops

else blocks after, 2325

iterator protocol and, 4042

Fraction class, for numerical precision, 172

Functions

closure/variable scope interaction, 3136

decorated, 151153

docstrings for, 178179

exceptions vs. return None, 2931

as first-class objects, 32, 6364

generator vs. returning lists, 3638

iterating over arguments, 3842

keyword arguments for, 4548

keyword-only arguments for, 5154

optional positional arguments for, 4345

for simple interfaces, 6164

simultaneous, coroutines for, 137138

functools built-in module, for defining decorators, 152153

G

Game of Life, coroutines in, 138143

Garbage collector, cleanup by, 99

gc built-in module, debugging memory usage, 214215

Generator(s)

coroutine extensions of, 137138

expressions, for large comprehensions, 1820

returning lists vs., 3638

Generic class method, for constructing objects, 6769

Generic functionality, with mix-in classes, 7478

__get__ method, for descriptor protocol, 97100

__getattr__ special method, to lazily load attributes, 100103

__getattribute__ method, accessing instance variables in, 104105

__getattribute__ method, descriptor protocol and, 98100

__getattribute__ special method, for repeated access, 102105

__getitem__ special method

custom implementation of, 8486

in slicing sequences, 10

Getter methods

descriptor protocol for, 98100

problems with using, 8788

providing with @property, 8889

GIL (global interpreter lock)

corruption of data structures and, 126127

defined, 122

preventing parallelism in threads, 122125, 145, 146147

Global scope, 33

H

hasattr built-in function, determining existence of properties, 103

hashlib built-in module, 120

heappop function, for priority queues, 168169

heappush function, for priority queues, 168169

heapq module, for priority queues, 168169

help function

decorator problems with, 152153

in interactive debugger, 208

Helper classes

for bookkeeping, 5860

providing stateful closure behavior, 6263

Helper functions, complex expressions into, 810

Hooks

to access missing attributes, 100105

default value, 6264

functions acting as, 6162

in modifying class properties, 113

I

IEEE 754 (IEEE Standard for Floating-Point Arithmetic), 171172

if/else expressions, for simplification, 910

import * statements

avoiding, 183184

in providing stable APIs, 182183

Import paths, stable, copyreg providing, 161162

Import reordering, for circular dependencies, 189190

import statements

as dynamic imports, 191192

with packages, 180181

Incrementing in place, public attributes for, 88

index method, for custom container types, 8586

Infinite recursion, super() function avoiding, 101105

Inheritance

from collections.abc, 8486

method resolution order (MRO) and, 71

multiple, for mix-in utility classes, 7778

__init__ method

as single constructor per class, 67, 69

initializing parent class, 6971

__init__.py

defining packages, 180

modifying, 182

Initializing parent classes

__init__ method for, 6971

method resolution order (MRO) and, 71

super built-in function for, 7073

Integration tests, 207

Interactive debugging, with pdb, 208209

Intermediate root exceptions, future-proofing APIs, 186187

I/O (input/output)

between child processes, 118121

threads for blocking I/O, 124125

IOError, except blocks and, 2627

IronPython runtime, 1, 2

isinstance

bytes/str/unicode and, 56

with coroutines, 142

dynamic type inspection with, 7475

metaclasses and, 114

pickle module and, 158

testing and, 205

islice function, of itertools module, 170

iter built-in function, 4142

__iter__ method

as generator, 4142

iterable container class, defined, 4142

Iterator protocol, 4042

Iterators

as function arguments, 39

generators returning, 3738

zip function processing, 2123

itertools built-in module

functions of, 169170

izip_longest function, for iterating in parallel, 23

J

join method, of Queue class, 132136

Jython runtime, 1, 2

K

Keyword arguments

constructing classes with, 58

dynamic default argument values, 4851

providing optional behavior, 4548

Keyword-only arguments

for clarity, 5153

in Python 2, 5354

L

lambda expression

as key hook, 61

vs. list comprehensions, 1516

producing iterators and, 40

in profiling, 210212

Language hooks, for missing attributes, 100105

Lazy attributes, __getattr__/__setattr__/__getattribute__ for, 100105

_leading_underscore format, 3

Leaky bucket quota, implementing, 9295

len built-in function, for custom sequence types, 85

__len__ special method, for custom sequence types, 85

list built-in type, performance as FIFO queue, 166167

List comprehensions

generator expressions for, 1820

instead of map/filter, 1516

number of expressions in, 1618

list type, subclassing, 8384

Lists, slicing, 1013

locals built-in function, 152, 208

localtime function, from time module, 163164

Lock class

preventing data races, 126129

in with statements, 153154

Logging

debug function for, 154156

severity levels, 154155

Loops

else blocks after, 2325

in list comprehensions, 1618

range/enumerate functions, 2021

lowercase_underscore format, 3

M

map built-in function, list comprehensions vs., 1516

Memory

coroutine use of, 137

threads requiring, 136

Memory leaks

by descriptor classes, 99100

identifying, 214216

Memory management, with tracemalloc module, 214216

Meta.__new__ method

in metaclasses, 107

setting class attributes, 114

__metaclass__ attribute, in Python 2, 106107

Metaclasses

annotating attributes with, 112115

for class registration, 108112

defined, 87, 106

validating subclasses, 105108

method resolution order (MRO), for superclass initialization order, 7073

Mix-in classes

composing from simple behaviors, 7475

defined, 7374

pluggable behaviors for, 7576

utility, creating hierachies of, 7778

mktime, for time conversion, 163, 165

Mock functions and classes

unittest.mock built-in module, 206

__module__ attribute, 106, 153

Modules

breaking circular dependencies in, 187192

community-built, 173174

docstrings, 176177

packages for organizing, 179184

providing stable APIs from, 181184

tailoring for deployment environment, 199201

Module-scoped code, for deployment environments, 199201

MRO (method resolution order), for superclass initialization order, 7073

Multiple conditions, in list comprehensions, 1618

Multiple inheritance, for mix-in utility classes, 7378

Multiple iterators, zip built-in function and, 2123

Multiple loops, in list comprehensions, 1618

multiprocessing built-in module, enabling parallelism, 146148

Mutual-exclusion locks (mutex)

GIL as, 122

Lock class as, 126129

in with statements, 153154

N

__name__ attribute in defining decorators, 151, 153

in registering classes, 109110

testing and, 206

namedtuple type

defining classes, 58

limitations of, 59

NameError exception, 33

Namespace packages, with Python 3.4, 180

Naming conflicts, private attributes to avoid, 8182

Naming styles, 34

ncalls column in profiler statistics, 211

__new__ method, of metaclasses, 106108

next built-in function, 4142

next command, of interactive debugger, 209

__next__ special method, iterator object implementing, 41

Noise reduction, keyword arguments and, 4548

None value

functions returning, 2931

specifying dynamic default values, 4851

nonlocal statement, in closures modifying variables, 3435

nsmallest function, for priority queues, 168169

Numerical precision, with Decimal class, 171173

O

Objects, accessing missing attributes in, 100105

On-the-fly calculations, using @property for, 9195

Optimization, profiling prior to, 209213

Optional arguments

keyword, 4748

positional, 4345

OrderedDict class, for dictionaries, 167168

OverflowError exceptions, 51

P

Packages

dividing modules into namespaces, 180181

as modules containing modules, 179180

providing stable APIs with, 181184

Parallelism

avoiding threads for, 122123

child processes and, 118121

concurrent.futures for true, 146148

corruption of data structures and, 126128

defined, 117

need for, 145146

Parent classes

accessing private attributes of, 7981

initializing, 7073

pdb built-in module, for interactive debugging, 208209

pdb.set_trace() statements, 208209

PEP 8 (Python Enhancement Proposal #8) style guide

expression/statement rules, 4

naming styles in, 34, 80

overview of, 23

whitespace rules, 3

permutations function, of itertools module, 170

pickle built-in module

adding missing attribute values, 159160

providing stable import paths for, 161162

serializing/deserializing objects, 157158

versioning classes for, 160161

pip command-line tool

reproducing environments, 196197

transitive dependencies and, 192193

for utilizing Package Index, 173

pip freeze command, saving package dependencies, 196

Pipelines

concurrency in, 129131

problems with, 132

Queue class building, 132136

Polymorphism

@classmethods utilizing, 6569

defined, 64

Popen constructor, starting child processes, 118

Positional arguments

constructing classes with, 58

keyword arguments and, 4548

reducing visual noise, 4345

print function, for debugging output, 202203, 208

print_stats output, for profiling, 213

Printable representation, repr function for, 202204

Private attributes

accessing, 7880

allowing subclass access to, 8183

indicating internal APIs, 80

ProcessPoolExecutor class, enabling parallelism, 147148

product function, of itertools module, 170

Production environment, unique configurations for, 199201

profile module, liabilities of, 210

@property method

defining special behavior with, 8889

descriptors for reusing, 97100

giving attributes new functionality, 9194

improving data models with, 95

numerical attributes, into on-the-fly calculations, 9195

problems with overusing, 9596

unexpected side effects in, 9091

@property.setter, modifying object state in, 91

pstats built-in module, extracting statistics, 211

Public attributes

accessing, 78

defining new class interfaces with, 8788

giving new functionality to, 9194

preferred features of, 8082

Pylint tool, for Python source code, 4

PyPI (Python Package Index), for community-built modules, 173174

PyPy runtime, 1, 2

Python 2

coroutines in, 143145

determining use of, 2

keyword-only arguments in, 5354

metaclass syntax in, 106107

mutating closure variables in, 35

str and unicode in, 57

zip built-in function in, 22

Python 3

class decorators in, 111

determining use of, 2

closures and nonlocal statements in, 3435

keyword-only arguments in, 5153

metaclass syntax in, 106

str and bytes in, 57

Python Enhancement Proposal #8. See PEP 8 (Python Enhancement Proposal #8) style guide

Python Package Index (PyPI), for community-built modules, 173174

Python threads. See Threads

pytz module

installing, 173

pyvenv tool and, 194

for time conversions, 165166

pyvenv command-line tool

purpose of, 194

reproducing environments, 196197

for virtual environments, 194196

Q

quantize method, of Decimal class, for numerical data, 172

Queue class, coordinating work between threads, 132136

R

range built-in function, in loops, 20

Read the Docs community-funded site, 176

Refactoring attributes, @property instead of, 9195

Refactoring code, for circular dependencies, 189

Registering classes, metaclasses for, 108112

Repetitive code

composing mix-ins to minimize, 74

keyword arguments eliminating, 4548

__repr__ special method, customizing class printable representation, 203204

repr strings, for debugging output, 202204

requirements.txt file, for installing packages, 197

return command, of interactive debugger, 209

return statements

in generators, 140

not allowed in Python 2 generators, 144

Root exceptions

finding bugs in code with, 185186

future-proofing APIs, 186187

insulating callers from APIs, 184185

Rule of least surprise, 87, 90, 91

runcall method, for profiling, 211213

S

Scopes, variable, closure interaction with, 3136

Scoping bug, in closures, 34

select built-in module, blocking I/O, 121, 124

Serializing, data structures, 109

Serializing objects, pickle and

default argument approach to, 159160

default attribute values and, 159160

pickle built-in module for, 157158

stable import paths and, 161162

__set__ method, for descriptor protocol, 97100

set_trace function, pdb module running, 208209

setattr built-in function

annotating class attributes and, 113

in bad thread interactions, 127128

lazy attributes and, 101102, 104

__setattr__ special method, to lazily set attributes, 103105

__setitem__ special method, in slicing sequences, 10

Sets, comprehension expressions in, 16

setter attribute, for @property method, 8889

Setter methods

descriptor protocol for, 98100

liability of using, 8788

providing with @property, 8889

setuptools, in virtual environments, 195197

Single constructor per class, 67, 69

Single-line expressions, difficulties with, 810

six tool, in adopting Python 3, 2

Slicing sequences

basic functions of, 1013

stride syntax in, 1315

Sort, key argument, closure functions as, 3132

source bin/activate command, enabling pyvenv tool, 195

Speedup, concurrency vs. parallelism for, 117

Star args (*args), 43

start indexes, in slicing sequences, 1013

Statements, PEP 8 guidance for, 4

Static type checking, lack of, 204205

Stats object, for profiling information, 211213

step command, of interactive debugger, 209

StopIteration exception, 39, 41

str instances, for character sequences, 57

stride syntax, in slicing sequences, 1315

strptime functions, conversion to/from local time, 163164

Subclasses

allowing access to private fields, 8183

constructing/connecting generically, 6569

list type, 8384

TestCase, 206207

validating with metaclasses, 105108

subprocess built-in module, for child processes, 118121

super built-in function, initializing parent classes, 7173

super method, avoiding infinite recursion, 101105

Superclass initialization order, MRO resolving, 7073

Syntax

decorators, 151153

for closures mutating variables, 3435

for keyword-only arguments, 5253

loops with else blocks, 23

list comprehensions, 15

metaclasses, 106

slicing, 1013

SyntaxError exceptions, dynamic imports and, 192

sys module, guiding module definitions, 201

System calls, blocking I/O and, 124125

T

takewhile function, of itertools module, 170

task_done call, method of the Queue class, in building pipelines, 134

tee function, of itertools module, 170

Test methods, 206207

TestCase classes, subclassing, 206207

threading built-in module, Lock class in, 126129

ThreadPoolExecutor class, not enabling parallelism, 147148

Threads

blocking I/O and, 124125

coordinating work between, 132136

parallelism prevented by, 122123, 145, 146147

preventing data races between, 126129

problems with, 136

usefulness of multiple, 124

time built-in module, limitations of, 163164

Time zone conversion methods, 162166

timeout parameter, in child process I/O, 121

tottime column, in profiler statistics, 211

tottime percall column, in profiler statistics, 211

tracemalloc built-in module, for memory optimization, 214216

Transitive dependencies, 192194

try/except statements, root exceptions and, 185

try/except/else/finally blocks, during exception handling, 2728

try/finally blocks

during exception handling, 2627

with statements providing reusable, 154155

Tuples

extending, 58

rules for comparing, 32

as values, 57

variable arguments becoming, 44

zip function producing, 2123

TypeError

exceptions, for keyword-only arguments, 5354

rejecting iterators, 4142

tzinfo class, for time zone operations, 164165

U

unicode instances, for character sequences, 57

Unit tests, 207

unittest built-in module, for writing tests, 205207

UNIX timestamp, in time conversions, 163165

Unordered dictionaries, 167

up command, of interactive debugger, 209

UTC (Coordinated Universal Time), in time conversions, 162165

Utility classes, mix-in, creating hierarchies of, 7778

V

Validation code, metaclasses running, 105108

ValueError exceptions, 3031, 184

Values

from iterators, 4042

tuples as, 57

validating assignments to, 89

Variable positional arguments

keyword arguments and, 4748

reducing visual noise, 4345

Variable scopes, closure interaction with, 3136

--version flag, determining version of Python, 12

Virtual environments

pyvenv tool creating, 194196

reproducing, 196197

virtualenv command-line tool, 194

Visual noise, positional arguments reducing, 4345

W

WeakKeyDictionary, purpoose of, 99

weakref module, building descriptors, 113

while loops, else blocks following, 2325

Whitespace, importance of, 3

Wildcard imports, 183

with statements

mutual-exclusion locks with, 153154

for reusable try/finally blocks, 154155

as target values and, 155156

wraps helper function, from functools, for defining decorators, 152153

Y

yield expression

in coroutines, 137138

in generator functions, 37

use in contextlib, 155

yield from expression, unsupported in Python 2, 144

Z

ZeroDivisionError exceptions, 3031, 51

zip built-in function

for iterators of different lengths, 170

processing iterators in parallel, 2123

zip_longest function, for iterators of different length, 2223, 170

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.142.194