SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
Introduction to functional programming in
Python
Francesco Bruni

@brunifrancesco 

Original notebook @ https://github.com/brunifrancesco/cds_talk
Who am I
• MSc Student in Telecommunication Engineering @ Poliba (Italy)

• Despite a Java background, I prefer Python whenever possible

• Data science addicted
What we'll talk about
	 •	 Why functional programming

	 •	 Why Python

	 •	 Functional features in Python

	 ▪	 First class functions

	 ▪	 Immutable vs mutable data

	 ▪	 Lazy evaluation

	 ▪	 Recursion vs loop

	 ▪	 (Manual) Currying

	 ▪	 Monads

	 •	 Useful functional programming resources

	 •	 Conclusions
Why functional programming
	 •	 Think in terms of functions

	 •	 State as function evaluation, not variables assignment

	 •	 Testing is (more) easy

	 •	 A new viewpoint is required
import random

def sum_imperative():

res = 0

for n in [random.random() for _ in range(100)]:

res += n

return res

def sum_functional():

return sum(random.random() for _ in range(100))
Why Python
There are a lot of languages out there..
Pros
	 •	 Mature enough

	 •	 Multiparadigm and multipurpose

	 •	 Easy to learn

	 •	 Interactive shell

	 •	 Multiple implementantions (C, Java, Python, .NET, Ruby, Js)

	 •	 Extending requires few lines of code
Cons
	 •	 Python 3 vs Python 2

	 •	 No typed variables

	 •	 CPython is the widest used implementation

	 •	 Changing implementation/version is not (always) a free iussues transition
Functional features in Python
	 •	 Not all functional patterns apply to Python

	 •	 Hybrid approach is often requested

	 •	 Other libraries needs to be (eventually) integrated
First class functions
	 •	 Functions are objects too

	 •	 They have fields too and some basic methods
def func_1(x="32"):

assert(x)

def func_2():

return "wow!"

func_3 = lambda some_param: str(some_param)
High order functions
	 •	 Functions which accept functions as params;

	 •	 Functions which return other functions;

	 •	 Python std lib examples for mapping: filter, map, sorted,

	 •	 Python std lib examples for reducing: max, min, sum

Task: given the previous generated list, filter some number out and sort the result by the
second digit.
def filter_out():



result = python_better_approach()



exclude = map(lambda item: item ** 2, range(30))

result = filter(lambda item: item not in exclude, result)



return sorted(result, key=lambda item: str(item)[1])



filter(lambda item: item not in map(lambda item: item ** 2, range(30)),
python_better_approach(size=100))
Class for function composition
Handle class creation via a new class syntax, allowing a "static" configuration
from collections.abc import Callable

class ExcludeFunction(Callable):

def __init__(self, exclude_function):

self.exclude_function= exclude_function



def __call__(self, value):

return None if not value else self.exclude_function(value)

result = python_better_approach(size=100)

exclude_function_1 = lambda item: item ** 2

ex_func = ExcludeFunction(exclude_function_1)

result = filter(lambda item: not item == ex_func(item), result)

assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
Immutable vs mutable data structure
	 •	 Since state is not given by variable assignement, there's no need of mutables data

	 •	 (Almost) no classes are required

	 •	 Instead of lists, tuples are reccomanded

	 •	 Instead of classes, namedtuple can be used
from collections.abc import Callable

class ExcludeFunction(Callable):

def __init__(self, exclude_function):

self.exclude_function= exclude_function



def __call__(self, value):

return None if not value else self.exclude_function(value)

result = python_better_approach(size=100)

exclude_function_1 = lambda item: item ** 2

ex_func = ExcludeFunction(exclude_function_1)

result = filter(lambda item: not item == ex_func(item), result)

assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
Strict vs not strict evaluation
	 •	 Strict evaluation requires that all operators needs to be evaluated

	 •	 Non strict (or lazy) evaluation, evaluates expression if and when requested
Use case: Python iterables structures
• Iterable: objects than can be iterated;

• Iterator: objects than can be iterated and consumed only once, with two main problems:

	 ▪	 They track their state in a stateful object

	 ▪	 Their values are generated a priori

	 ▪	 They aren't lazy

• Generators: lazy evaluated data structures:

	 ▪	 They track state in function, instead of object

	 ▪	 They don't act as normal functions

	 ▪	 They generate next member when invoked
def _iter(size=100):

return iter(python_better_approach(size=size))

def lazy_python_approach(size=100):

for item in range(10, size):

if not item % 2 and not str(item).endswith("4"):

yield item

def lazy_new_python_approach(size=100):

yield from (r for r in range(10, size) if not r % 2 and not str(r).endswith("4"))
Recursion vs loop
	 •	 Functional programming requires a recursion approach vs loop iteration

	 •	 Python suffers by recursion limit

	 •	 Python does not offer any tail call optimization
def fact_loop(n):

if n == 0: return 1

f= 1

for i in range(2,n):

f *= i

return f

def fact(n):

if n == 0: return 1

else: return n*fact(n-1)
Currying
Multiple arguments functions mapped to single arguments functions
from random import randrange

def mult(a, b, c ):

def wrapper_1(b):

def wrapper_2(c):

return a*b*c

return wrapper_2(c)

return wrapper_1(b)

def mult_2(a):

def wrapper_1(b):

def wrapper_2(c):

return a*b*c

return wrapper_2

return wrapper_1
Partials
Python provides "partial" functions for manual currying
from functools import reduce

import operator

import random

def two_random_sum():

return reduce(operator.sum, [random.random()]*2)

def three_random_product():

return reduce(operator.mul, [random.random()]*3)

def four_random_sub():

return reduce(operator.sub, [random.random()]*4)

def five_random_pow ():

return reduce(operator.pow, [random.random()]*5)
def handle_random_numbers(size, function):

return reduce(function, [random.random()]*size)

two_random_sum = partial(handle_random_numbers, size=2)

three_random_sum = partial(handle_random_numbers, size=3)

two_random_pow = partial(handle_random_numbers, size=2, function=operator.pow)

five_random_product = partial(handle_random_numbers, size=5, function=operator.mul)
Decorator Pattern
Return a modified version of a decorated function
from functools import wraps

from functools import partial

def get_ned_data(n):

def get_doubled_data(func, *args, **kwargs):

@wraps(func)

def _inner(*args, **kwargs):

kwargs["new_param"] = kwargs["some_param"]*n

return func(*args, **kwargs)

return _inner

return get_doubled_data
@get_ned_data(n=2)

def double_func(*args, **kwargs):

assert(kwargs["new_param"] == kwargs["some_param"]*2)

@get_ned_data(n=3)

def triple_func(*args, **kwargs):

assert(kwargs["new_param"] == kwargs["some_param"]*3)



double_func(some_param=3)

triple_func(some_param=5)
Monads
	 •	 How to handle errors in functional programming?

	 •	 Practical example: parsing and transforming data coming from HTTP request

	 •	 Python "std" libs have no support
from fn.monad import optionable

def get(request, *args, **kwargs):

@optionable

def _get_values(data):

return data.get("values", None)

_split = lambda item: item.split(",")

_strip = lambda item: item.replace(" ", "")

_filter = lambda item: list(filter(lambda i: i, item))

values = _get_values(request.GET).map(_strip).map(_split).map(_filter).get_or(["v1,v2"])

return values
from collections import namedtuple

def test():

_req_class = namedtuple("Request", ("GET"))



request_1 = _req_class(dict(values="v1, v2,v3"))

request_2 = _req_class(dict(values="v1,v2,v3 "))

request_3 = _req_class(dict(values="v1, v2,v3, "))



assert(get(request_1) == ['v1', 'v2', 'v3'])

assert(get(request_2) == ['v1', 'v2', 'v3'])

assert(get(request_3) == ['v1', 'v2', 'v3'])
@get_object(MeterInstance)

def post(self, request, *args, **kwargs):

@optionable

def get_data(data):

return data.get("data", None)

return get_data(request.DATA)

.map(

lambda item:

handle_error_configuration(item, kwargs["contatore"]))

.map(

lambda item:

Response(dict(detail=item), status=200))

.get_or(Response("BadRequest", status=400))
Useful libraries
• Fn.py (https://github.com/kachayev/fn.py) (A bit of Scala, ported to Python)

• Underscore.py (ported from underscore_js)
Summary
	 •	 Functional programming for writing more succint code

	 •	 Change viewpoint: think in terms of functions

	 •	 Python seems for dummies until you show some cool features

	 •	 Python can be slow but with a fine tuning can be more efficient
Questions?

Mais conteúdo relacionado

Mais procurados

Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2Hariz Mustafa
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresIntellipaat
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
julia-Latest Programming language
julia-Latest Programming  languagejulia-Latest Programming  language
julia-Latest Programming languageNithya Prakasan
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and SimpleBen Mabey
 

Mais procurados (20)

Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python Closures
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
julia-Latest Programming language
julia-Latest Programming  languagejulia-Latest Programming  language
julia-Latest Programming language
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 

Destaque

Club degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parteClub degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parteGiuseppe Toto
 
ANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compilerANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compilerGiuseppe Santoro
 
Containing the world with Docker
Containing the world with DockerContaining the world with Docker
Containing the world with DockerGiuseppe Piccolo
 
Club degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° ParteClub degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° ParteGiuseppe Toto
 
Sencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parteSencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parteGiuseppe Toto
 
Sencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceSencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceGiuseppe Toto
 
Customer centric agile @ ACE! conference
Customer centric agile @ ACE! conferenceCustomer centric agile @ ACE! conference
Customer centric agile @ ACE! conferenceAngel Diaz-Maroto
 
Alberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italianaAlberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italianaLa Scuola Open Source
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approachFrancesco Bruni
 
Basic NLP with Python and NLTK
Basic NLP with Python and NLTKBasic NLP with Python and NLTK
Basic NLP with Python and NLTKFrancesco Bruni
 
Continuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and JenkinsContinuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and JenkinsFrancesco Bruni
 
NoSQL databases pros and cons
NoSQL databases pros and consNoSQL databases pros and cons
NoSQL databases pros and consFabio Fumarola
 
Metricas Ingenieria De Software
Metricas Ingenieria De SoftwareMetricas Ingenieria De Software
Metricas Ingenieria De SoftwareRicardo
 
How to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environmentHow to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environmentMichelantonio Trizio
 

Destaque (16)

Club degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parteClub degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parte
 
ANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compilerANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compiler
 
Containing the world with Docker
Containing the world with DockerContaining the world with Docker
Containing the world with Docker
 
Club degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° ParteClub degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° Parte
 
Sencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parteSencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parte
 
Open street map
Open street mapOpen street map
Open street map
 
Sencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceSencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codice
 
Customer centric agile @ ACE! conference
Customer centric agile @ ACE! conferenceCustomer centric agile @ ACE! conference
Customer centric agile @ ACE! conference
 
Alberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italianaAlberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italiana
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
Basic NLP with Python and NLTK
Basic NLP with Python and NLTKBasic NLP with Python and NLTK
Basic NLP with Python and NLTK
 
Continuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and JenkinsContinuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and Jenkins
 
NoSQL databases pros and cons
NoSQL databases pros and consNoSQL databases pros and cons
NoSQL databases pros and cons
 
Metricas Ingenieria De Software
Metricas Ingenieria De SoftwareMetricas Ingenieria De Software
Metricas Ingenieria De Software
 
How to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environmentHow to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environment
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
 

Semelhante a Introduction to Functional Programming

Slide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptxSlide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptxLucidAxel
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdfpaijitk
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfDaddy84
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 

Semelhante a Introduction to Functional Programming (20)

Slide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptxSlide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptx
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Functional python
Functional pythonFunctional python
Functional python
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 

Último

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Último (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Introduction to Functional Programming

  • 1. Introduction to functional programming in Python Francesco Bruni @brunifrancesco Original notebook @ https://github.com/brunifrancesco/cds_talk
  • 2. Who am I • MSc Student in Telecommunication Engineering @ Poliba (Italy) • Despite a Java background, I prefer Python whenever possible • Data science addicted
  • 3. What we'll talk about • Why functional programming • Why Python • Functional features in Python ▪ First class functions ▪ Immutable vs mutable data ▪ Lazy evaluation ▪ Recursion vs loop ▪ (Manual) Currying ▪ Monads • Useful functional programming resources • Conclusions
  • 4. Why functional programming • Think in terms of functions • State as function evaluation, not variables assignment • Testing is (more) easy • A new viewpoint is required
  • 5. import random def sum_imperative(): res = 0 for n in [random.random() for _ in range(100)]: res += n return res def sum_functional(): return sum(random.random() for _ in range(100))
  • 6. Why Python There are a lot of languages out there..
  • 7. Pros • Mature enough • Multiparadigm and multipurpose • Easy to learn • Interactive shell • Multiple implementantions (C, Java, Python, .NET, Ruby, Js) • Extending requires few lines of code
  • 8. Cons • Python 3 vs Python 2 • No typed variables • CPython is the widest used implementation • Changing implementation/version is not (always) a free iussues transition
  • 9. Functional features in Python • Not all functional patterns apply to Python • Hybrid approach is often requested • Other libraries needs to be (eventually) integrated
  • 10. First class functions • Functions are objects too • They have fields too and some basic methods
  • 11. def func_1(x="32"): assert(x) def func_2(): return "wow!" func_3 = lambda some_param: str(some_param)
  • 12. High order functions • Functions which accept functions as params; • Functions which return other functions; • Python std lib examples for mapping: filter, map, sorted, • Python std lib examples for reducing: max, min, sum Task: given the previous generated list, filter some number out and sort the result by the second digit.
  • 13. def filter_out(): result = python_better_approach() exclude = map(lambda item: item ** 2, range(30)) result = filter(lambda item: item not in exclude, result) return sorted(result, key=lambda item: str(item)[1]) filter(lambda item: item not in map(lambda item: item ** 2, range(30)), python_better_approach(size=100))
  • 14. Class for function composition Handle class creation via a new class syntax, allowing a "static" configuration
  • 15. from collections.abc import Callable class ExcludeFunction(Callable): def __init__(self, exclude_function): self.exclude_function= exclude_function def __call__(self, value): return None if not value else self.exclude_function(value) result = python_better_approach(size=100) exclude_function_1 = lambda item: item ** 2 ex_func = ExcludeFunction(exclude_function_1) result = filter(lambda item: not item == ex_func(item), result) assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
  • 16. Immutable vs mutable data structure • Since state is not given by variable assignement, there's no need of mutables data • (Almost) no classes are required • Instead of lists, tuples are reccomanded • Instead of classes, namedtuple can be used
  • 17. from collections.abc import Callable class ExcludeFunction(Callable): def __init__(self, exclude_function): self.exclude_function= exclude_function def __call__(self, value): return None if not value else self.exclude_function(value) result = python_better_approach(size=100) exclude_function_1 = lambda item: item ** 2 ex_func = ExcludeFunction(exclude_function_1) result = filter(lambda item: not item == ex_func(item), result) assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
  • 18. Strict vs not strict evaluation • Strict evaluation requires that all operators needs to be evaluated • Non strict (or lazy) evaluation, evaluates expression if and when requested
  • 19. Use case: Python iterables structures • Iterable: objects than can be iterated; • Iterator: objects than can be iterated and consumed only once, with two main problems: ▪ They track their state in a stateful object ▪ Their values are generated a priori ▪ They aren't lazy • Generators: lazy evaluated data structures: ▪ They track state in function, instead of object ▪ They don't act as normal functions ▪ They generate next member when invoked
  • 20. def _iter(size=100): return iter(python_better_approach(size=size)) def lazy_python_approach(size=100): for item in range(10, size): if not item % 2 and not str(item).endswith("4"): yield item def lazy_new_python_approach(size=100): yield from (r for r in range(10, size) if not r % 2 and not str(r).endswith("4"))
  • 21. Recursion vs loop • Functional programming requires a recursion approach vs loop iteration • Python suffers by recursion limit • Python does not offer any tail call optimization
  • 22. def fact_loop(n): if n == 0: return 1 f= 1 for i in range(2,n): f *= i return f def fact(n): if n == 0: return 1 else: return n*fact(n-1)
  • 23. Currying Multiple arguments functions mapped to single arguments functions
  • 24. from random import randrange def mult(a, b, c ): def wrapper_1(b): def wrapper_2(c): return a*b*c return wrapper_2(c) return wrapper_1(b) def mult_2(a): def wrapper_1(b): def wrapper_2(c): return a*b*c return wrapper_2 return wrapper_1
  • 25. Partials Python provides "partial" functions for manual currying
  • 26. from functools import reduce import operator import random def two_random_sum(): return reduce(operator.sum, [random.random()]*2) def three_random_product(): return reduce(operator.mul, [random.random()]*3) def four_random_sub(): return reduce(operator.sub, [random.random()]*4) def five_random_pow (): return reduce(operator.pow, [random.random()]*5)
  • 27. def handle_random_numbers(size, function): return reduce(function, [random.random()]*size) two_random_sum = partial(handle_random_numbers, size=2) three_random_sum = partial(handle_random_numbers, size=3) two_random_pow = partial(handle_random_numbers, size=2, function=operator.pow) five_random_product = partial(handle_random_numbers, size=5, function=operator.mul)
  • 28. Decorator Pattern Return a modified version of a decorated function
  • 29. from functools import wraps from functools import partial def get_ned_data(n): def get_doubled_data(func, *args, **kwargs): @wraps(func) def _inner(*args, **kwargs): kwargs["new_param"] = kwargs["some_param"]*n return func(*args, **kwargs) return _inner return get_doubled_data
  • 30. @get_ned_data(n=2) def double_func(*args, **kwargs): assert(kwargs["new_param"] == kwargs["some_param"]*2) @get_ned_data(n=3) def triple_func(*args, **kwargs): assert(kwargs["new_param"] == kwargs["some_param"]*3) double_func(some_param=3) triple_func(some_param=5)
  • 31. Monads • How to handle errors in functional programming? • Practical example: parsing and transforming data coming from HTTP request • Python "std" libs have no support
  • 32. from fn.monad import optionable def get(request, *args, **kwargs): @optionable def _get_values(data): return data.get("values", None) _split = lambda item: item.split(",") _strip = lambda item: item.replace(" ", "") _filter = lambda item: list(filter(lambda i: i, item)) values = _get_values(request.GET).map(_strip).map(_split).map(_filter).get_or(["v1,v2"]) return values
  • 33. from collections import namedtuple def test(): _req_class = namedtuple("Request", ("GET")) request_1 = _req_class(dict(values="v1, v2,v3")) request_2 = _req_class(dict(values="v1,v2,v3 ")) request_3 = _req_class(dict(values="v1, v2,v3, ")) assert(get(request_1) == ['v1', 'v2', 'v3']) assert(get(request_2) == ['v1', 'v2', 'v3']) assert(get(request_3) == ['v1', 'v2', 'v3'])
  • 34. @get_object(MeterInstance) def post(self, request, *args, **kwargs): @optionable def get_data(data): return data.get("data", None) return get_data(request.DATA) .map( lambda item: handle_error_configuration(item, kwargs["contatore"])) .map( lambda item: Response(dict(detail=item), status=200)) .get_or(Response("BadRequest", status=400))
  • 35. Useful libraries • Fn.py (https://github.com/kachayev/fn.py) (A bit of Scala, ported to Python) • Underscore.py (ported from underscore_js)
  • 36. Summary • Functional programming for writing more succint code • Change viewpoint: think in terms of functions • Python seems for dummies until you show some cool features • Python can be slow but with a fine tuning can be more efficient