Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Functional Python Programming, 3rd edition
Functional Python Programming, 3rd edition

Functional Python Programming, 3rd edition: Use a functional approach to write succinct, expressive, and efficient Python code , Third Edition

eBook
€8.99 €28.99
Paperback
€35.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Functional Python Programming, 3rd edition

 2
Introducing Essential Functional Concepts

Most of the features of functional programming are already part of the Python language. Our goal in writing functional Python is to shift our focus away from imperative (procedural or object-oriented) techniques as much as possible.

We’ll look at the following functional programming topics:

  • In Python, functions are first-class objects.

  • We can use and create higher-order functions.

  • We can create pure functions very easily.

  • We can work with immutable data.

  • In a limited way, we can create functions that have non-strict evaluation of sub-expressions. Python generally evaluates expressions strictly. As we’ll see later, a few operators are non-strict.

  • We can design functions that exploit eager versus lazy evaluation.

  • We can use recursion instead of an explicit loop state.

  • We have a type system that can apply to functions and objects.

This expands on the concepts from the first chapter: firstly, that purely functional programming...

2.1 Functions as first-class objects

Functional programming is often succinct and expressive. One way to achieve this is by providing functions as arguments and return values for other functions. We’ll look at numerous examples of manipulating functions.

For this to work, functions must be first-class objects in the runtime environment. In programming languages such as C, a function is not a runtime object; because the compiled C code generally lacks internal attributes and methods, there’s little runtime introspection that can be performed on a function. In Python, however, functions are objects that are created (usually) by def statements and can be manipulated by other Python functions. We can also create a function as a callable object or by assigning a lambda object to a variable.

Here’s how a function definition creates an object with attributes:

>>> def example(a, b, **kw): 
...     return a*b 
... 
>>> type(example) ...

2.2 Immutable data

Since we’re not using variables to track the state of a computation, our focus needs to stay on immutable objects. We can make extensive use of tuples, typing.NamedTuples, and frozen @dataclass to provide more complex data structures that are also immutable. We’ll look at these class definitions in detail in Chapter 7, Complex Stateless Objects.

The idea of immutable objects is not foreign to Python. Strings and tuples are two widely-used immutable objects. There can be a performance advantage to using immutable tuples instead of more complex mutable objects. In some cases, the benefits come from rethinking the algorithm to avoid the costs of object mutation.

As an example, here’s a common design pattern that works well with immutable objects: the wrapper() function. A list of tuples is a fairly common data structure. We will often process this list of tuples in one of the two following ways:

  • Using higher-order functions: As shown earlier...

2.3 Strict and non-strict evaluation

Functional programming’s efficiency stems, in part, from being able to defer a computation until it’s required. There are two similar concepts for avoiding computation. These are:

  • Strictness: Python operators are generally strict and evaluate all sub-expressions from left to right. This means an expression like f(a)+f(b)+f(c) is evaluated as if it was (f(a)+f(b))+f(c). An optimizing compiler might avoid strict ordering to improve performance. Python doesn’t optimize and code is mostly strict. We’ll look at cases where Python is not strict below.

  • Eagerness and laziness: Python operators are generally eager and evaluate all sub-expressions to compute the final answer. This means (3-3) * f(d) is fully evaluated even though the first part of the multiplication—the (3-3) sub-expression—is always zero, meaning the result is always zero, no matter what value is computed by the expression f(d). Generator...

2.4 Lazy and eager evaluation

Python’s generator expressions and generator functions are lazy. These expressions don’t create all possible results immediately. It’s difficult to see this without explicitly logging the details of a calculation. Here is an example of the version of the range() function that has the side effect of showing the numbers it creates:

from collections.abc import Iterator 
def numbers(stop: int) -> Iterator[int]: 
    for i in range(stop): 
        print(f"{i=}") 
        yield i

To provide some debugging hints, this function prints each value as the value is yielded. If this function were eager, evaluating numbers(1024) would take the time (and storage) to create all 1,024 numbers. Since the numbers() function is lazy, it only creates a number as it is requested.

We can use this noisy numbers() function in a...

2.5 Recursion instead of an explicit loop state

Functional programs don’t rely on loops and the associated overhead of tracking the state of loops. Instead, functional programs try to rely on the much simpler approach of recursive functions. In some languages, the programs are written as recursions, but Tail-Call Optimization (TCO) in the compiler changes them to loops. We’ll introduce some recursion here and examine it closely in Chapter 6, Recursions and Reductions.

We’ll look at an iteration to test whether a number is a prime number. Here’s a definition from https://mathworld.wolfram.com/PrimeNumber.html: “A prime number ... is a positive integer p > 1 that has no positive integer divisors other than 1 and p itself.” We can create a naive and poorly performing algorithm to determine whether a number has any factors between 2 and the number. This is called the Trial Division algorithm. It has the advantage of simplicity; it works acceptably...

2.6 Functional type systems

Some functional programming languages, such as Haskell and Scala, are statically compiled, and depend on declared types for functions and their arguments. To provide the kind of flexibility Python already has, these languages have sophisticated type-matching rules allowing a generic function to work for a variety of related types.

In object-oriented Python, we often use the class inheritance hierarchy instead of sophisticated function type matching. We rely on Python to dispatch an operator to a proper method based on simple name-matching rules.

Python’s built-in ”duck typing” rules offer a great deal of type flexibility. The more complex type matching rules for a compiled functional language aren’t relevant. It’s common to define a typing.Protocol to specify the features an object must have. The actual class hierarchy doesn’t matter; what matters is the presence of the appropriate methods and attributes.

Python’...

2.7 Familiar territory

One of the ideas that emerges from the previous list of topics is that many functional programming constructs are already present in Python. Indeed, elements of functional programming are already a very typical and common part of OOP.

As a very specific example, a fluent Application Program Interface (API) is a very clear example of functional programming. If we take time to create a class with return self in each method, we can use it as follows:

some_object.foo().bar().yet_more()

We can just as easily write several closely related functions that work as follows:

yet_more(bar(foo(some_object)))

We’ve switched the syntax from traditional object-oriented suffix notation to a more functional prefix notation. Python uses both notations freely, often using a prefix version of a special method name. For example, the len() function is generally implemented by the __len__() class special method.

Of course, the implementation of the preceding class might involve...

2.8 Learning some advanced concepts

We will set some more advanced concepts aside for consideration in later chapters. These concepts are part of the implementation of a purely functional language. Since Python isn’t purely functional, our hybrid approach won’t require deep consideration of these topics.

We will identify these here for the benefit of readers who already know a functional language such as Haskell and are learning Python. The underlying concerns are present in all programming languages, but we’ll tackle them differently in Python. In many cases, we can and will drop into imperative programming rather than use a strictly functional approach.

The topics are as follows:

  • Referential transparency: When looking at lazy evaluation and the various kinds of optimizations that are possible in a compiled language, the idea of multiple routes to the same object is important. In Python, this isn’t as important because there aren’t any relevant compile...

2.9 Summary

In this chapter, we’ve identified a number of features that characterize the functional programming paradigm. We started with first-class and higher-order functions. The idea is that a function can be an argument to a function or the result of a function. When functions become the object of additional programming, we can write some extremely flexible and generic algorithms.

The idea of immutable data is sometimes odd in an imperative and object-oriented programming language such as Python. When we start to focus on functional programming, however, we see a number of ways that state changes can be confusing or unhelpful. Using immutable objects can be a helpful simplification.

Python focuses on strict evaluation: all sub-expressions are evaluated from left to right through the statement. Python, however, does perform some non-strict evaluation. The or, and, and if-else logical operators are non-strict: all sub-expressions are not necessarily evaluated.

Generator functions...

2.10 Exercises

This chapter’s exercises are based on code available from Packt Publishing on GitHub. See https://github.com/PacktPublishing/Functional-Python-Programming-3rd-Edition.

In some cases, the reader will notice that the code provided on GitHub includes partial solutions to some of the exercises. These serve as hints, allowing the reader to explore alternative solutions.

In many cases, exercises will need unit test cases to confirm they actually solve the problem. These are often identical to the unit test cases already provided in the GitHub repository. The reader should replace the book’s example function name with their own solution to confirm that it works.

2.10.1 Apply map() to a sequence of values

Some analysis has revealed a consistent measurement error in a device. The machine’s revolutions per minute (RPM) as displayed on the tachometer are consistently incorrect. (Gathering the true RPM involves some heroic engineering effort, but is not a sustainable...

Join our community Discord space

Join our Python Discord workspace to discuss and know more about the book: https://packt.link/dHrHU

PIC

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how, when, and why to adopt functional elements in your projects
  • Explore the Python modules essential to functional programming, like itertools and functools
  • Cover examples relevant to mathematical, statistical, and data analysis domains

Description

Not enough developers understand the benefits of functional programming, or even what it is. Author Steven Lott demystifies the approach, teaching you how to improve the way you code in Python and make gains in memory use and performance. If you’re a leetcoder preparing for coding interviews, this book is for you. Starting from the fundamentals, this book shows you how to apply functional thinking and techniques in a range of scenarios, with Python 3.10+ examples focused on mathematical and statistical algorithms, data cleaning, and exploratory data analysis. You'll learn how to use generator expressions, list comprehensions, and decorators to your advantage. You don't have to abandon object-oriented design completely, though – you'll also see how Python's native object orientation is used in conjunction with functional programming techniques. By the end of this book, you'll be well-versed in the essential functional programming features of Python and understand why and when functional thinking helps. You'll also have all the tools you need to pursue any additional functional topics that are not part of the Python language.

Who is this book for?

The functional paradigm is very useful for programmers working in data science or preparing for technical interviews, but any Python developer who wants to create more reliable, succinct, and expressive code will have much to learn from this book. No prior knowledge of functional programming is required to get started, though Python programming knowledge is assumed. A running Python environment is essential.

What you will learn

  • Use Python's libraries to avoid the complexities of state-changing classes
  • Leverage built-in higher-order functions to avoid rewriting common algorithms
  • Write generator functions to create lazy processing
  • Design and implement decorators for functional composition
  • Make use of Python type annotations to describe parameters and results of functions
  • Apply functional programming to concurrency and web services
  • Explore the PyMonad library for stateful simulations

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 30, 2022
Length: 576 pages
Edition : 3rd
Language : English
ISBN-13 : 9781803236568
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 30, 2022
Length: 576 pages
Edition : 3rd
Language : English
ISBN-13 : 9781803236568
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 109.97
Functional Python Programming, 3rd edition
€35.99
Mastering Python 2E
€37.99
Advanced Python Programming
€35.99
Total 109.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Chapter 1: Understanding Functional Programming Chevron down icon Chevron up icon
Chapter 2: Introducing Essential Functional Concepts Chevron down icon Chevron up icon
Chapter 3: Functions, Iterators, and Generators Chevron down icon Chevron up icon
Chapter 4: Working with Collections Chevron down icon Chevron up icon
Chapter 5: Higher-Order Functions Chevron down icon Chevron up icon
Chapter 6: Recursions and Reductions Chevron down icon Chevron up icon
Chapter 7: Complex Stateless Objects Chevron down icon Chevron up icon
Chapter 8: The Itertools Module Chevron down icon Chevron up icon
Chapter 9: Itertools for Combinatorics – Permutations and Combinations Chevron down icon Chevron up icon
Chapter 10: The Functools Module Chevron down icon Chevron up icon
Chapter 11: The Toolz Package Chevron down icon Chevron up icon
Chapter 12: Decorator Design Techniques Chevron down icon Chevron up icon
Chapter 13: The PyMonad Library Chevron down icon Chevron up icon
Chapter 14: The Multiprocessing, Threading, and Concurrent.Futures Modules Chevron down icon Chevron up icon
Chapter 15: A Functional Approach to Web Services Chevron down icon Chevron up icon
Other Books You Might Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(28 Ratings)
5 star 71.4%
4 star 17.9%
3 star 3.6%
2 star 0%
1 star 7.1%
Filter icon Filter
Top Reviews

Filter reviews by




Carlos Andres Jaramillo Feb 21, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book Functional Python Programming is an excellent book for anyone who wants to deepen their learning of Python, with very clear examples and challenging exercises the author fills the reader with a deep understanding of this wonderful programming language. I highly recommend this book for people who want to acquire a Senior level in Python or who want to optimize their algorithms at the enterprise level.El libro Functional Python Programming, es un excelente libro para todo el que quiera profundizar en el aprendizaje de Python, con ejemplos muy claros y ejercicios retadores el autor va llenando al lector a una comprensión profunda de este maravilloso lenguaje de programación. Recomiendo mucho este libro para las personas que desean adquirir un nivel Senior en Python o que quieren optimizar sus algoritmos a nivel empresarial.
Amazon Verified review Amazon
Michael Jan 03, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This Book strengthened my ability to exploit pythons facilities for functional programming. Taking a more functional approach sometimes you can get a lot more done. Then when you combine that with the OOP is a whole new world!
Amazon Verified review Amazon
srikar Jan 12, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book explains excellent explanation on functional programming concept. This book is not intended for beginner students. For anyone who wants to read this book must have solid python understanding and working experience.The author covered functional programming with python for almost all the major topics in programming such as multi threading and also other topics such as web services which gives an excellent insight on how to use functional programming with python. The exercises are also good which gives good insight on some of the edge case problems. Overall it's an excellent read for an experienced programmer.
Amazon Verified review Amazon
Andre P. Feb 04, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book provides a smooth introduction to the world of functional programming. It illustrates the core concepts of functional programming (like high-order functions, decorators, generators and iterators) and shows how it’s possible to leverage standard library modules (like IterTools and FuncTools, for instance) to simplify the task of writing functional code. The book has plenty of code samples (which are available on GitHub) that make it really easy to understand and follow the content. I would highly recommend it to anybody looking to familiarize themselves with functional programming.My personal book highlights are:✔️ Higher-Order Functions✔️ Decorator Design Techniques✔️ The Multiprocessing, Threading, and Concurrent.Futures Modules✔️ A Functional Approach to Web Services
Amazon Verified review Amazon
v Jan 06, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers many important topics for functional programming in python from intermediate to advanced levels. Both junior (with some python basis) and senior readers can find useful information from the book. As well, this book also provides good examples for readers.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.