The Python Apprentice

Book description

Learn the Python skills and culture you need to become a productive member of any Python project.

About This Book

  • Taking a practical approach to studying Python
  • A clear appreciation of the sequence-oriented parts of Python
  • Emphasis on the way in which Python code is structured
  • Learn how to produce bug-free code by using testing tools

Who This Book Is For

The Python Apprentice is for anyone who wants to start building, creating and contributing towards a Python project. No previous knowledge of Python is required, although at least some familiarity with programming in another language is helpful.

What You Will Learn

  • Learn the language of Python itself
  • Get a start on the Python standard library
  • Learn how to integrate 3rd party libraries
  • Develop libraries on your own
  • Become familiar with the basics of Python testing

In Detail

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it's not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.

Style and approach

We introduce topics gently and then revisit them on multiple occasions to add the depth required to support your progression as a Python developer. We've worked hard to structure the syllabus to avoid forward references. On only a few occasions do we require you to accept techniques on trust, before explaining them later; where we do, it's to deliberately establish good habits.

Publisher resources

Download Example Code

Table of contents

  1. Preface
    1. Python Promo
    2. Overview
    3. What is Python?
      1. It's a programming language!
        1. Versions of the Python language
      2. It's a standard library!
      3. It's a philosophy
    4. The journey of a thousand miles…
    5. Errata and Suggestions
    6. Conventions Used in This Book
    7. Downloading the example code
    8. Downloading the color images of this book
  2. Getting started
    1. Obtaining and installing Python 3
      1. Windows
      2. macOS
      3. Linux
    2. Starting Python command line REPL
    3. Leaving the REPL
      1. Windows
      2. Unix
    4. Code structure and significant indentation
    5. Python culture
    6. Importing standard library modules
    7. Getting help()
      1. Counting fruit with math.factorial()
      2. Different types of numbers
    8. Scalar data types: integers, floats, None and bool
      1. int
      2. float
        1. Special floating point values
        2. Promotion to float
      3. None
      4. bool
    9. Relational operators
      1. Rich comparison operators
    10. Control flow: if-statements and while-loops
      1. Conditional control flow: The if-statement
      2. if...else
      3. if...elif...else
      4. Conditional repetition: the while-loop
        1. Exiting loops with break
    11. Summary
  3. Strings and Collections
    1. str – an immutable sequence of Unicode code points
      1. String quoting styles
    2. Moment of zen
      1. Concatenation of adjacent strings
      2. Multiline strings and newlines
      3. Raw strings
        1. The str constructor
      4. Strings as sequences
      5. String methods
    3. Strings with Unicode
    4. The bytes type  – an immutable sequence of bytes
      1. Literal bytes
      2. Converting between bytes and str
    5. list – a sequence of objects
    6. The dict type – associating keys with values
    7. The For-loops – iterating over series of items
    8. Putting it all together
    9. Summary
  4. Modularity
    1. Organizing code in a .py file
      1. Running Python programs from the operating system shell
      2. Importing modules into the REPL
    2. Defining functions
    3. Organizing our module into functions
      1. The __name__  type and executing modules from the command line
    4. The Python execution model
      1. The difference between modules, scripts, and programs
    5. Setting up a main function with command line argument
      1. Accepting command line arguments
    6. Moment of zen
    7. Docstrings
    9. Shebang
      1. Executable Python programs on Linux and Mac
      2. Executable Python programs on Windows
      3. Summary
  5. Built-in types and the object model
    1. The nature of Python object references
      1. Reassigning a reference
      2. Assigning one reference to another
      3. Exploring value vs. identity with id()
      4. Testing for equality of identity with is
      5. Mutating without mutating
      6. References to mutable objects
      7. Equality of value (equivalence) versus equality of identity
    2. Argument passing semantics – pass by object-reference
      1. Modifying external objects in a function
      2. Binding new objects in a function
      3. Argument passing is reference binding
    3. Python return semantics
    4. Function arguments in detail
      1. Default parameter values
      2. Keyword arguments
      3. When are default arguments evaluated?
    5. The Python type system
      1. Dynamic typing in Python
      2. Strong typing in Python
    6. Variable declaration and scoping
      1. The LEGB rule
    7. Scopes in action
      1. Identical names in global and local scope
      2. The global keyword
    8. Moment of zen
    9. Everything is an object
      1. Inspecting a function
    10. Summary
  6. Exploring Built-in Collection types
    1. tuple – an immutable sequence of objects
      1. Literal tuples
      2. Tuple element access
        1. The length of a tuple
      3. Iterating over a tuple
      4. Concatenating and repetition of tuples
        1. Nested tuples
      5. Single-element tuples
      6. Empty tuples
      7. Optional parentheses
      8. Returning and unpacking tuples
      9. Swapping variables with tuple unpacking
    2. The tuple constructor
      1. Membership tests
    3. Strings in action
      1. The length of a string
      2. Concatenating strings
      3. Joining strings
      4. Splitting strings
    4. Moment of zen
      1. Partitioning strings
      2. String formatting
      3. Other string methods
    5. range – a collection of evenly spaced integers
      1. Starting value
      2. Step argument
      3. Not using range: enumerate()
    6. list in action
      1. Negative indexing for lists (and other sequences)
      2. Slicing lists
      3. Copying lists
      4. Shallow copies
      5. Repeating lists
      6. Finding list elements with index()
      7. Membership testing with count() and in
      8. Removing list elements by index with del
      9. Removing list elements by value with remove()
      10. Inserting into a list
      11. Concatenating lists
      12. Rearranging list elements
      13. Out-of-place rearrangement
    7. Dictionaries
      1. Copying dictionaries
      2. Updating dictionaries
      3. Iterating over dictionary keys
      4. Iterating over dictionary values
      5. Iterating over key-value pairs
      6. Membership testing for dictionary keys
      7. Removing dictionary items
      8. Mutability of dictionaries
      9. Pretty printing
    8. set – an unordered collection of unique elements
      1. The set constructor
      2. Iterating over sets
      3. Membership testing of sets
      4. Adding elements to sets
      5. Removing elements from sets
      6. Copying sets
      7. Set algebra operations
      8. Union
        1. Intersection
      9. Difference
        1. Symmetric difference
        2. Subset relationships
    9. Collection protocols
      1. Container protocol
      2. Sized protocol
      3. Iterable protocol
      4. Sequence protocol
      5. Other protocols
    10. Summary
  7. Exceptions
    1. Exceptions and control flow
      1. Handling exceptions
    2. Handling multiple exceptions
    3. Programmer errors
    4. Empty blocks – the pass statement
    5. Exception objects
    6. Imprudent return codes
    7. Re-raising exceptions
    8. Exceptions are part of your function's API
      1. Exceptions raised by Python
      2. Catching exceptions
      3. Raising exceptions explicitly
    9. Guard clauses
    10. Exceptions, APIs, and protocols
      1. IndexError
      2. ValueError
      3. KeyError
    11. Choosing not to guard against TypeError
    12. Pythonic style – EAFP versus LBYL
    13. Clean-up actions
    14. Moment of zen
    15. Platform-specific code
    16. Summary
  8. Comprehensions, iterables, and generators
    1. Comprehensions
      1. List comprehensions
        1. List comprehension syntax
        2. Elements of a list comprehension
      2. Set comprehensions
      3. Dictionary comprehensions
        1. Comprehension complexity
      4. Filtering comprehensions
        1. Combining filtering and transformation
    2. Moment of zen
    3. Iteration protocols
      1. An example of the iteration protocols
      2. A more practical example of the iteration protocols
    4. Generator functions
      1. The yield keyword
      2. Generators are iterators
      3. When is generator code executed?
      4. Maintaining explicit state in the generator function
        1. The first stateful generator: take()
        2. The second stateful generator: distinct()
        3. Understand these generators!
        4. Lazy generator pipelines
      5. Laziness and the infinite
        1. Generating the Lucas series
    5. Generator expressions
    6. Batteries included iteration tools
      1. Introducing itertools
      2. Sequences of booleans
      3. Merging sequences with zip
        1. More than two sequences with zip()
      4. Lazily concatenating sequences with chain()
    7. Pulling it all together
    8. Summary
      1. Generators
      2. Iteration tools
  9. Defining new types with classes
    1. Defining classes
    2. Instance methods
    3. Instance initializers
      1. A lack of access modifiers
    4. Validation and invariants
    5. Adding a second class
    6. Collaborating classes
    7. Moment of zen
    8. Booking seats
      1. Allocating seats to passengers
    9. Naming methods for implementation details
      1. Implementing relocate_passenger()
      2. Counting available seats
    10. Sometimes the only object you need is a function
      1. Making Flight create boarding cards
    11. Polymorphism and duck-typing
      1. Refactoring Aircraft
    12. Inheritance and implementation sharing
      1. A base class for aircraft
      2. Inheriting from Aircraft
      3. Hoisting common functionality into a base class
    13. Summary
  10. Files and Resource Management
    1. Files
      1. Binary and text modes
      2. The important of encoding
      3. Opening a file for writing
      4. Writing to files
      5. Closing files
      6. The file outside of Python
      7. Reading files
        1. Readline line by line
        2. Reading multiple lines at once
      8. Appending to files
      9. File objects as iterators
    2. Context Managers
      1. Managing resources with finally
      2. The with-blocks
    3. Moment of zen
    4. Binary files
      1. The BMP file format
      2. Bitwise operators
      3. Writing a BMP file
        1. Reading binary files
    5. File-like objects
      1. You've already seen file-like objects!
      2. Using file-like objects
    6. Other resources
    7. Summary
  11. Unit testing with the Python standard library
    1. Test cases
    2. Fixtures
    3. Assertions
    4. Unit testing example: text analysis
      1. Running the initial tests
      2. Making the test pass
    5. Using fixtures to create temporary files
    6. Using the new fixtures
    7. Using assertions to test behavior
      1. Counting lines
      2. Counting characters
    8. Testing for exceptions
    9. Testing for file existence
    10. Moment of zen
    11. Summary
  12. Debugging with PDB
    1. Debugging commands
    2. Palindrome debugging
      1. Bug hunting with PDB
      2. Finding infinite loops with sampling
      3. Setting explicit breaks
      4. Stepping through execution
      5. Fixing the bug
    3. Summary
  13. Afterword – Just the Beginning
  14. Virtual Environments
    1. Creating a virtual environment
    2. Activating a virtual environment
    3. Deactivating a virtual environment
    4. Other tools for working with virtual environments
  15. Packaging and Distribution
    1. Configuring a package with distutils
    2. Installing with distutils
    3. Packaging with distutils
  16. Installing Third-Party Packages
    1. Installing pip
    2. The Python Package Index
      1. Installing with pip
    3. Installing Local Packages with pip
    4. Uninstalling Packages

Product information

  • Title: The Python Apprentice
  • Author(s): Robert Smallshire, Austin Bingham
  • Release date: June 2017
  • Publisher(s): Packt Publishing
  • ISBN: 9781788293181