SlideShare a Scribd company logo
Functional
Programming
inside OOP?
It’s possible with Python
>>>whoami()
Carlos Villavicencio
● Ecuadorian 󰎸
● Currently: Python & TypeScript
● Community leader
● Martial arts: 剣道、居合道
● Nature photography enthusiast
Cayambe Volcano, 2021.
po5i
>>>why_functional_programming
● Easier and efficient
● Divide and conquer
● Ease debugging
● Makes code simpler and readable
● Also easier to test
>>>history()
● Functions were first-class objects from design.
● Users wanted more functional solutions.
● 1994: map, filter, reduce and lambdas were included.
● In Python 2.2, lambdas have access to the outer scope.
“Not having the choice streamlines the thought process.”
- Guido van Rossum.
The fate of reduce() in Python 3000
https://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html
>>>has_django_fp()
https://github.com/django/django/blob/46786b4193e04d398532bbfc3dcf63c03c1793cb/django/forms/formsets.py#L201-L213
https://github.com/django/django/blob/ca9872905559026af82000e46cde6f7dedc897b6/django/forms/formsets.py#L316-L328
Immutability An immutable object is an object
whose state cannot be modified after
it is created.
Booleans, strings, and integers are
immutable objects.
List and dictionaries are mutable
objects.
Thread safety
def update_list(value: list) -> None:
value += [10]
>>>immutability
>>> foo = [1, 2, 3]
>>> id(foo)
4479599424
>>> update_list(foo)
>>> foo
[1, 2, 3, 10]
>>> id(foo)
4479599424
def update_number(value: int) -> None:
value += 10
>>> foo = 10
>>> update_number(foo)
>>> foo
10
🤔
def update_number(value: int) -> None:
print(value, id(value))
value += 10
print(value, id(value))
>>>immutability
>>> foo = 10
>>> update_number(foo)
10 4478220880
20 4478221200
>>> foo
10
https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747
󰚃
Decorators They are functions which modify the
functionality of other functions.
Higher order functions.
Closures?
>>>decorators
def increment(x: int) -> int:
return x + 1
>>> increment(2)
3
>>>decorators
def increment(x: int) -> int:
return x + 1
def double_increment(func: Callable) -> Callable:
def wrapper(x: int):
r = func(x) # func is saved in __closure__
y = r * 2
return y
return wrapper
>>>decorators
@double_increment
def increment(x: int) -> int:
return x + 1
>>> increment(2)
6
>>> increment.__closure__[0].cell_contents
<function increment at 0x7eff362cf940>
>>> increment.__closure__[0].cell_contents(2)
3
They reduce the number of arguments
that any function takes.
Makes functions easier to compose
with others.
Partial application
of functions
>>>partial_application
def get_url(url: str, role: str) -> str:
pass
from functools import partial
get_admin_url = partial(get_url, "admin")
>>>partial_application
import re
from functools import partial
email_match = partial(re.match, r"^(w|.|_|-)+[@](w|_|-|.)+[.]w{2,3}$")
url_match = partial(re.match,
r"(?i)b((?:https?://|wwwd{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}/)(?:[^s()<>]+|(([^s()<>
]+|(([^s()<>]+)))*))+(?:(([^s()<>]+|(([^s()<>]+)))*)|[^s`!()[]{};:'".,<>?
«»“”‘’]))")
Lazy Evaluation It holds the evaluation of an
expression until the value is finally
needed.
Reduce the memory footprint.
>>>lazy_evaluation
def generator():
i = 1
while True:
yield i
i += 1
>>>lazy_evaluation
with open(filename, 'r') as f:
for line in f:
process(line)
Type Annotations PEP 484
Available since Python 3.5
Reduce bugs at runtime
Improves readability
>>>__annotations__
Read tutorial at
stackbuilders.com
Watch my talk at
PyCon China 2020
Structural Pattern
Matching
PEP-634
Available since Python 3.10
It doesn’t work as C or JavaScript
It’s a declarative approach!
>>>structural_pattern_matching
# point is an (x, y) tuple[int, int]
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y) if x == y: # guard
print(f"X=Y={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _: # wildcard
raise ValueError("Not a point")
https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching
>>>structural_pattern_matching
# test_variable is a tuple[str, Any, int]
match test_variable:
case ('warning', code, 40):
print("A warning has been received.")
case ('error', code, _):
print(f"An error {code} occurred.")
Other Functional
Programming
Patterns
When Python doesn’t offer a way to
do it, you can always implement it.
Currying
Composition
>>>currying
If a function ƒn
takes n arguments, then you can turn that into a
function cn
which takes one argument and returns a function cn−1
that takes n−1 arguments, and has access to the argument that
was passed to cn
(hence cn−1
is a closure)
https://sagnibak.github.io/blog/python-is-haskell-currying/
>>>currying
def f_5(a: int, b: int, c: int, d: int, e: int) -> int:
return a + b + c + d + e
>>>currying
def c_5(a: int) -> Callable:
def c_4(b: int) -> Callable:
def c_3(c: int) -> Callable:
def c_2(d: int) -> Callable:
def c_1(e: int): int:
return f_5(a, b, c, d, e)
return c_1
return c_2
return c_3
return c_4
Then, f_5(1, 2, 3, 4, 5) == c_5(1)(2)(3)(4)(5)
@curry(num_args=5)
def c_5(a: int, b: int, c: int, d: int, e: int) -> int:
a + b + c + d + e
>>>currying
https://sagnibak.github.io/blog/python-is-haskell-currying/
>>>composition
▶ cat .env|grep DEBUG
ASSETS_DEBUG=True
SENTRY_DEBUG=False
>>>composition
sortByDateDescending = reverse . sortByDate
>>>composition
def compose2(f, g):
return lambda x: f(g(x))
https://mathieularose.com/function-composition-in-python
import functools
def compose(*functions):
def compose2(f, g):
return lambda x: f(g(x))
return functools.reduce(compose2, functions, lambda x: x)
>>>composition
def td(val: str) -> str:
return f"<td>{val}</td>"
def tr(val: str) -> str:
return f"<tr>{val}</tr>"
def table(val: str) -> str:
return f"<table>{val}</table>"
>>> one_cell_table = compose(table, tr, td)
>>> one_cell_table("something")
'<table><tr><td>something</td></tr></table>'
>>>composition
Testing Everything we covered before makes
our tests easier.
>>>import unittest
“Code that is hard to test is not good code”
- Joe Eames.
https://dev.to/leolanese/making-unit-test-fun-again-with-functional-programming-4g8m
>>>import unittest
“The outcome of a function is dependent only on the input and nothing else”
- Unknown author.
https://dev.to/leolanese/making-unit-test-fun-again-with-functional-programming-4g8m
>>>import unittest
“OO makes code understandable by encapsulating moving parts.
FP makes code understandable by minimizing moving parts.”
- Michael Feathers.
https://dev.to/leolanese/making-unit-test-fun-again-with-functional-programming-4g8m
Thank you for your
attention 😊
Questions?
Feedback?
Suggestions?
po5i

More Related Content

What's hot (20)

PDF
Bytes in the Machine: Inside the CPython interpreter
akaptur
 
PDF
Phil Bartie QGIS PLPython
Ross McDonald
 
PDF
Functional programming in Python
Colin Su
 
PDF
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
akaptur
 
PPT
Euro python2011 High Performance Python
Ian Ozsvald
 
PDF
Swift the implicit parts
Maxim Zaks
 
PPT
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
 
PPTX
Programming Homework Help
Programming Homework Help
 
PDF
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
PDF
Docopt
René Ribaud
 
PPTX
20170317 functional programming in julia
岳華 杜
 
PDF
Welcome to python
Kyunghoon Kim
 
PPTX
20170714 concurrency in julia
岳華 杜
 
PDF
Haskell 101
Roberto Pepato
 
PPTX
Lecture no 3
hasi071
 
PDF
Javascript
Vlad Ifrim
 
PDF
Imugi: Compiler made with Python
Han Lee
 
PDF
FEAL - CSAW CTF 2014 Quals Crypto300
YOKARO-MON
 
PDF
Python Programming: Data Structure
Chan Shik Lim
 
Bytes in the Machine: Inside the CPython interpreter
akaptur
 
Phil Bartie QGIS PLPython
Ross McDonald
 
Functional programming in Python
Colin Su
 
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
akaptur
 
Euro python2011 High Performance Python
Ian Ozsvald
 
Swift the implicit parts
Maxim Zaks
 
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
 
Programming Homework Help
Programming Homework Help
 
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Docopt
René Ribaud
 
20170317 functional programming in julia
岳華 杜
 
Welcome to python
Kyunghoon Kim
 
20170714 concurrency in julia
岳華 杜
 
Haskell 101
Roberto Pepato
 
Lecture no 3
hasi071
 
Javascript
Vlad Ifrim
 
Imugi: Compiler made with Python
Han Lee
 
FEAL - CSAW CTF 2014 Quals Crypto300
YOKARO-MON
 
Python Programming: Data Structure
Chan Shik Lim
 

Similar to Functional Programming inside OOP? It’s possible with Python (20)

PDF
Rethink programming: a functional approach
Francesco Bruni
 
PDF
Python functional programming
Geison Goes
 
PDF
Introduction to Functional Programming
Francesco Bruni
 
PDF
Functional python
Jesué Junior
 
PPTX
Functional programming in python
Edward D. Weinberger
 
PDF
Functional programming in python
Edward D. Weinberger
 
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PDF
PythonOOP
Veera Pendyala
 
PDF
Functional Objects in Ruby: new horizons – Valentine Ostakh
Ruby Meditation
 
PPTX
Functional Programming.pptx
KarthickT28
 
PPTX
Why functional programming in C# & F#
Riccardo Terrell
 
PDF
Some basic FP concepts
Falko Riemenschneider
 
PDF
Functions in python
Ilian Iliev
 
PPT
An Overview Of Python With Functional Programming
Adam Getchell
 
PDF
Functional Programming with Groovy
Arturo Herrero
 
PDF
A tour of Python
Aleksandar Veselinovic
 
PDF
An overview of Python 2.7
decoupled
 
PDF
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
PDF
Functional programming
ijcd
 
PPTX
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Rethink programming: a functional approach
Francesco Bruni
 
Python functional programming
Geison Goes
 
Introduction to Functional Programming
Francesco Bruni
 
Functional python
Jesué Junior
 
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Edward D. Weinberger
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PythonOOP
Veera Pendyala
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Ruby Meditation
 
Functional Programming.pptx
KarthickT28
 
Why functional programming in C# & F#
Riccardo Terrell
 
Some basic FP concepts
Falko Riemenschneider
 
Functions in python
Ilian Iliev
 
An Overview Of Python With Functional Programming
Adam Getchell
 
Functional Programming with Groovy
Arturo Herrero
 
A tour of Python
Aleksandar Veselinovic
 
An overview of Python 2.7
decoupled
 
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
Functional programming
ijcd
 
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Ad

More from Carlos V. (6)

PDF
How to start using types in Python with mypy
Carlos V.
 
PDF
TID Chile dataviz
Carlos V.
 
PDF
Open Data in Agriculture - AGH20013 Hands-on session
Carlos V.
 
PPT
APIVITA BeeNet - Athens Green Hackathon 2013
Carlos V.
 
PPTX
Findjira presentación
Carlos V.
 
PDF
agINFRA Workshop for LACLO2012
Carlos V.
 
How to start using types in Python with mypy
Carlos V.
 
TID Chile dataviz
Carlos V.
 
Open Data in Agriculture - AGH20013 Hands-on session
Carlos V.
 
APIVITA BeeNet - Athens Green Hackathon 2013
Carlos V.
 
Findjira presentación
Carlos V.
 
agINFRA Workshop for LACLO2012
Carlos V.
 
Ad

Recently uploaded (20)

PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PDF
Letasoft Sound Booster 1.12.0.538 Crack Download+ Product Key [Latest]
HyperPc soft
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Tally software_Introduction_Presentation
AditiBansal54083
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Letasoft Sound Booster 1.12.0.538 Crack Download+ Product Key [Latest]
HyperPc soft
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Import Data Form Excel to Tally Services
Tally xperts
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 

Functional Programming inside OOP? It’s possible with Python