[Tutor] Functional Programming in Python
Steven D'Aprano
steve at pearwood.info
Thu Apr 2 20:07:13 CEST 2015
On Thu, Apr 02, 2015 at 12:18:28PM -0400, WolfRage wrote:
> These are just some questions that I have regarding the topic of
> Functional Programming. I am working towards a more functional approach
> to programming but acknowledge that it is far from Functional,
> especially since this is mostly impossible in Python.
It is true that Python is not a purely functional language, like
Haskell, but that does not stop you from writing code in a functional
style.
> Questions:
> What are the best practices to create more Functional Python?
Best practices:
* Don't force your code to use one style exclusively. Use the most
natural style for the task. Python makes it easy to mix functional,
procedural, imperative and object oriented code in the one
application. Use whatever is most natural for your task.
* Where possible, write your functions and methods in a functional
style. That means:
- Avoid global variables.
- Avoid side-effects where possible.
- Separate the logic of your algorithm from the display of results (e.g.
don't have a method that calculates a result AND prints it; have the
method calculate the result, and then have the caller print it).
- In Python 3, zip(), map() and filter() are lazy iterator functions; in
Python 2 they are eager, but there are lazy versions in the itertools
module.
- In Python 3, reduce() is moved to the functools module.
- Many uses of map() and filter() are better written as generator
expressions; e.g. instead of:
filter(lambda s: s.lower().startswith("a"), map(str, mylist))
you can use:
(str(x) for x in mylist if s.lower().startswith("a"))
- Where useful, write your code to take advantage of "pipelining"
style, e.g. using lazy iterators rather than lists. You can then chain
iterators together to get the desired result.
> What are your thoughts on Functional in Python?
> Currently I am re-writing functions to reduce their side effects.
> I am also removing the state from objects and putting it into a closure
> type function.
That doesn't remove state, it just moves it to a different place.
However, encapsulating state inside a closure, or an object, it often
the most effective and natural way to deal with a problem. Better than
passing around long and confusing numbers of variables!
> However with callback based systems (GUI) this seemed impossible, so
> instead I am abusing a coroutine to maintain the state of the application.
> But is it abuse or does it seem like a good way to handle the callback
> system? The benefit to me at this time is limited, but any errors in
> state are confined to a single location, which is nice.
> What do you think about using a coroutine to handle state, how would you
> do it better in a callback based system.
What do you mean? Can you show an example?
--
Steve
More information about the Tutor
mailing list