SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Thinking in Functions
atmb4u
CTO @ Profoundis Inc.
Agenda
★ Basics of Functional Programming
★ Functional Programming and Python
★ Everyday Functional Programming
★ Scaling with Functional Programming
★ Performance Implications
★ Data Explorations
House rules
★ Show of hands please
★ Ask anytime - Raise your hands
★ Be hands on
★ Free to use online resources
★ One step at a time
★ No-one left out policy
About Functional
Programming
About Functional
Programming ★ Formal Provability
About Functional
Programming ★ Modularity
About Functional
Programming
★ Ease of Debugging and
Testing
About Functional
Programming ★ Composability
Basics of Functional
Programming
★ Function as the atomic entity
○ First-class functions
○ Higher-order functions
○ Pure functions
Basics of Functional
Programming
★ Side Effects
○ Avoid state
○ Immutability
Basics of Functional
Programming ★ Lazy Evaluation
Basics of Functional
Programming ★ Type Systems
Basics of Functional
Programming
★ Recursion, Tail Recursion, Iterators,
Currying, Sequences, pattern matching,
monads....
Myths of Functional
Programming
★ It requires immutability/pureness
★ It requires an advanced type system
★ It is significantly less efficient
★ It makes you learn advanced math
★ You must give up all your imperative
programming notions
★ Object orientation and functional paradigms
are incompatible
★ Functional programs are easier to debug
★ Dynamic types are better than Static types
Functional methodology in Python
★ itertools and functools
★ Decorators and Generators
★ What python CAN do
○ lazy eval, lambda, map, reduce, filter
★ What python CANNOT do (pragmatically)
○ Eg: Tail Recursion, Pure immutability, Pure Functions
Functional Programming:
Done everyday
★ map
★ reduce
★ filter
★ enumerate
★ iter
★ list comprehension
★ Generator Expressions
★ Generators
★ itertools
★ functools
★ operator
★ decorator
★ Lambda Functions
List Comprehension
data = [1,2,3,4,5]
[item * 2 for item in data]
Generator Expression
data = [1,2,3,4,5]
generator_exp = (i*i for i in data)
sum(generator_exp)
operator module
import operator
operator.add(40,2)
operator.sub(45,3)
data = {'company': 'Acme Corp.'}
getCompany = operator.itemgetter('company')
getCompany(data)
enumerate
for item in enumerate(['subject', 'verb', 'object']):
print item
map
def upper(s):
return s.upper()
data = [“pycon”,”india”]
map(upper, data)
Map - Explained
from urllib import urlopen
urls = ['http://www.google.com',
'http://www.wikipedia.com',
'http://www.apple.com',
'http://www.python.org'
]
result = []
for item in urls:
result.append(urlopen(item))
return result
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
....
integers = [1, 2, 3, 4, 5]
result = []
for item in integers:
result.append(fib(item))
return result
?
Map - Explained
from urllib import urlopen
urls = ['http://www.google.com',
'http://www.wikipedia.com',
'http://www.apple.com',
'http://www.python.org'
]
result = []
for item in urls:
result.append(urlopen(item))
return result
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
...
integers = [1, 2, 3, 4, 5]
result = []
for item in integers:
result.append(fib(item))
return result
def map(function, sequence):
result = []
for item in sequence:
result.append(function(item))
return result
html_texts = map(urlopen, urls)
fib_integers = map(fib, integers)
Lambda
count_lambda =lambda w: len(w)
print map(count_lambda, 'It is raining cats and dogs'.split())
#conditions in lambda
lambda x: True if x % 2 == 0 else False
reduce
import operator
data = ["PyCon", "India", "2015"]
reduce(operator.concat, data)
Reduce - Explained
# Sum of a list of numbers
def add(x, y):
return x + y
def sum(data):
result = 0
for x in data:
result = add(result, x)
return result sum([5, 2, 3])
# Smallest in a list
def lesser(x, y):
if x < y:
return x
else:
return y
def min(data):
result = 999999999999
for x in data:
result = lesser(result, x)
return result min([5, 2, 3])
?
Reduce - Explained
# Sum of a list of numbers
def add(x, y):
return x + y
def sum(data):
result = 0
for x in data:
result = add(result, x)
return result sum([5, 2, 3])
# Smallest in a list
def lesser(x, y):
if x < y:
return x
else:
return y
def min(data):
result = 999999999999
for x in data:
result = lesser(result, x)
return result min([5, 2, 3])
# Sum
result = sum(data)
result = reduce(add, data, 0)
# Min
result = min(data)
result = reduce(lesser, data, 9999999999)
filter
def is_even(x):
return (x % 2) == 0
filter(is_even, range(10))
#even better
from itertools import ifilter
filter_iterator = ifilter(is_even,data)
filter_iterator.next()
iter function
numbers = [1,2,3]
it = iter(numbers)
# using while and StopIteration Exception
try:
while True:
print it.next()
except StopIteration:
print "Complete"
# as iterator in for loop
it = iter(numbers)
for value in it:
print value
import itertools
itertools.count(100)
itertools.cycle([1,2,3,4,5])
itertools.repeat("Hello", 5)
itertools - count, cycle, repeat
itertools - chain
it1 = iter([1, 2, 3])
it2 = iter([4, 5, 6])
itertools.chain(it1, it2)
itertools - groupby
city_list = [('Cochin', 'KL'),
('Bengaluru', 'KA'),
('Chennai', 'TN'),
('Mumbai', 'MH'),
('Trivandrum', 'KL'),
('Salem', 'TN'),
('Pune', 'MH')]
for city, city_iterator in groupby(city_list, lambda x: x[0]):
for city_state in city_iterator:
print "%s is in %s." % (city, city_state[1])
itertools - combinations, permutations
import itertools
itertools.permutations([1, 2, 3])
itertools.combinations([1, 2, 3, 4, 5], 2)
itertools - izip
dict(itertools.izip("ABCD", [1,2,3,4]))
#OR
zip("ABCD", [1,2,3,4])
functools - partial
import functools
def log (message, subsystem):
print '%s: %s' % (subsystem, message)
server_log = functools.partial(log,
subsystem='server')
server_log('Unable to open socket')
Decorators
def p_decorate(func):
def func_wrapper(name):
return "Super %s" func
(name)
return func_wrapper
@p_decorate
def get_text(name):
return "Hello %s" % name
print get_text("John")
Yield - creating custom generators
data_list = ["Orange", "Microsoft", "Apple"]
def one_at_a_time(data_list):
for item in data_list:
yield item
one_at_a_time.next()
Don't do unnecessary Classes
class Greeting(object):
def __init__(self, greeting="hello"):
self.greeting = greeting
def greet(self, name):
return "{greeting} {name}!".format
(greeting=greeting, name=name)
hola = Greeting("hola")
print hola.greet("bob")
or
?
Don't do unnecessary Classes
class Greeting(object):
def __init__(self, greeting="hello"):
self.greeting = greeting
def greet(self, name):
return "{greeting} {name}!".format
(greeting=greeting, name=name)
hola = Greeting("hola")
print hola.greet("bob")
def greet(greeting, name):
return "{greeting} {name}!".format(greeting=greeting,
name=name)
hello = functools.partial(greet, "Hello")
hello("Dude")
or
The Bad Parts
★ Memory Inefficiencies
★ Purity
★ No Tail Recursion
★ Innately imperative (Guido)
★ Class based type system
★ Only imperative Error Handling
(Exception)
★ Function Overloading
★ Mutable variables
Python vs Functional
Thinking about Scalability with Functions
★ map-reduce-filter - recipe for distributed computing
★ shared states- to be or not to be
★ immutable 'variables'
★ independent functions
★ Execution Pipelines - chained map-reduce
Performance v/s Scalability
★ Functional Programs vs Object Oriented Programs
★ CPU intensive processes vs I/O intensive processes
★ The curse of GIL - workarounds
○ multiprocessing
★ Benchmarking
○ %timeit
multiprocessing.Pool
import multiprocessing
def worker():
print 'Execute your function here'
return
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
// Why should I think in functions?
why!
★ no side effects -no state, no deadlocks, no semaphores
★ automatic parallelization - unlimited scalability
★ composability - break down into smaller functions
★ Testing -independent functions; well defined arguments and return values
★ partial evaluation - pass around half baked functions instead of objects
★ elegant code -forces to write logically correct programs
Hands On: Let’s do some Data Wrangling
Blockbuster Database (http://www.crowdflower.com/data-for-everyone)
➢ Which genre has most movies?
➢ Which movie studio gross the most?
➢ Sort by most grossed and Highly rated movies
demo code here
Questions
code samples in this presentation here
atm@profoundis.com
@atmb4u

Mais conteúdo relacionado

Mais procurados

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
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptDoug Sparling
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingKonrad Szydlo
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScriptWebF
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
 
Advance python programming
Advance python programming Advance python programming
Advance python programming Jagdish Chavan
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programmingnewmedio
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptWill Livengood
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingJordan Parmer
 

Mais procurados (20)

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
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with Javascript
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Scala functions
Scala functionsScala functions
Scala functions
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functional programming
Functional programmingFunctional programming
Functional programming
 

Destaque

Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
 
Cross Cultural Communication
Cross Cultural CommunicationCross Cultural Communication
Cross Cultural Communicationakshat saxena
 
Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...
Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...
Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...Gen Re
 
Make In India: a presentation openly ended for its Unlimited Applications
Make In India: a presentation openly ended for its Unlimited ApplicationsMake In India: a presentation openly ended for its Unlimited Applications
Make In India: a presentation openly ended for its Unlimited ApplicationsNaman Soni
 
PPt With animation on Mera Digital India
PPt With animation on Mera Digital IndiaPPt With animation on Mera Digital India
PPt With animation on Mera Digital IndiaAsh Gray
 
Digital strategy for a successful smart city initiative
Digital strategy for a successful smart city initiativeDigital strategy for a successful smart city initiative
Digital strategy for a successful smart city initiativeSaeed Al Dhaheri
 
El Futuro Del Trabajo Y El Trabajo Del Futuro
El Futuro Del Trabajo Y El Trabajo Del FuturoEl Futuro Del Trabajo Y El Trabajo Del Futuro
El Futuro Del Trabajo Y El Trabajo Del FuturoArturo Pelayo
 
Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...
Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...
Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...Smart Cities Project
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with pythonMarcelo Cure
 
What is Network Security?
What is Network Security?What is Network Security?
What is Network Security?Faith Zeller
 

Destaque (20)

Data Driven Code
Data Driven CodeData Driven Code
Data Driven Code
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
ingenium
ingeniumingenium
ingenium
 
Protoyping Painkiller Startups
Protoyping Painkiller StartupsProtoyping Painkiller Startups
Protoyping Painkiller Startups
 
Mapreduce in Python
Mapreduce in PythonMapreduce in Python
Mapreduce in Python
 
Web Development Fundamentals
Web Development FundamentalsWeb Development Fundamentals
Web Development Fundamentals
 
Cross Cultural Communication
Cross Cultural CommunicationCross Cultural Communication
Cross Cultural Communication
 
Digital life ppt 2
Digital life ppt 2Digital life ppt 2
Digital life ppt 2
 
Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...
Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...
Aktuelle Entwicklungen in der Lebensmittelindustrie und ihre Auswirkungen auf...
 
Make In India: a presentation openly ended for its Unlimited Applications
Make In India: a presentation openly ended for its Unlimited ApplicationsMake In India: a presentation openly ended for its Unlimited Applications
Make In India: a presentation openly ended for its Unlimited Applications
 
PPt With animation on Mera Digital India
PPt With animation on Mera Digital IndiaPPt With animation on Mera Digital India
PPt With animation on Mera Digital India
 
Digital strategy for a successful smart city initiative
Digital strategy for a successful smart city initiativeDigital strategy for a successful smart city initiative
Digital strategy for a successful smart city initiative
 
El Futuro Del Trabajo Y El Trabajo Del Futuro
El Futuro Del Trabajo Y El Trabajo Del FuturoEl Futuro Del Trabajo Y El Trabajo Del Futuro
El Futuro Del Trabajo Y El Trabajo Del Futuro
 
On digital india
On digital indiaOn digital india
On digital india
 
Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...
Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...
Creating Smarter Cities 2011 - 14 - Patrizia Lombardi - Triple Helix of Smart...
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with python
 
Android UI
Android UIAndroid UI
Android UI
 
Securing Windows web servers
Securing Windows web serversSecuring Windows web servers
Securing Windows web servers
 
SAN Review
SAN ReviewSAN Review
SAN Review
 
What is Network Security?
What is Network Security?What is Network Security?
What is Network Security?
 

Semelhante a Thinking in Functions: Functional Programming in Python

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super PowersPROIDEA
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basicsopenbala
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional ProgrammingSovTech
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: FunctionsMarc Gouw
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Romain Dorgueil
 
Simple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain DorgueilSimple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain DorgueilPôle Systematic Paris-Region
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||Ashwin Rao
 

Semelhante a Thinking in Functions: Functional Programming in Python (20)

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Functional python
Functional pythonFunctional python
Functional python
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
Python basic
Python basicPython basic
Python basic
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
 
Simple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain DorgueilSimple ETL in python 3.5+ with Bonobo, Romain Dorgueil
Simple ETL in python 3.5+ with Bonobo, Romain Dorgueil
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||
 
Functional programming
Functional programming Functional programming
Functional programming
 

Mais de Anoop Thomas Mathew

Writing Smarter Applications with Machine Learning
Writing Smarter Applications with Machine LearningWriting Smarter Applications with Machine Learning
Writing Smarter Applications with Machine LearningAnoop Thomas Mathew
 
Getting Started on distributed version control with git
Getting Started on distributed version control with gitGetting Started on distributed version control with git
Getting Started on distributed version control with gitAnoop Thomas Mathew
 
Advanced Computing for Sustainable Future
Advanced Computing for Sustainable FutureAdvanced Computing for Sustainable Future
Advanced Computing for Sustainable FutureAnoop Thomas Mathew
 
Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries Anoop Thomas Mathew
 
How slow is Real slow - PyCon India 2013
How slow is Real slow - PyCon India 2013 How slow is Real slow - PyCon India 2013
How slow is Real slow - PyCon India 2013 Anoop Thomas Mathew
 
Redis way of Anayltics with Python - Fifth Elephant 2012
Redis way of Anayltics with Python - Fifth Elephant 2012Redis way of Anayltics with Python - Fifth Elephant 2012
Redis way of Anayltics with Python - Fifth Elephant 2012Anoop Thomas Mathew
 
Building a Company atop of Open Source
Building a Company atop of Open SourceBuilding a Company atop of Open Source
Building a Company atop of Open SourceAnoop Thomas Mathew
 
Test Driven Development in Python
Test Driven Development in PythonTest Driven Development in Python
Test Driven Development in PythonAnoop Thomas Mathew
 

Mais de Anoop Thomas Mathew (14)

Writing Smarter Applications with Machine Learning
Writing Smarter Applications with Machine LearningWriting Smarter Applications with Machine Learning
Writing Smarter Applications with Machine Learning
 
What The Web!
What The Web!What The Web!
What The Web!
 
Investor pitch deck for Vibe
Investor pitch deck for VibeInvestor pitch deck for Vibe
Investor pitch deck for Vibe
 
Getting Started on distributed version control with git
Getting Started on distributed version control with gitGetting Started on distributed version control with git
Getting Started on distributed version control with git
 
Let's Contribute
Let's ContributeLet's Contribute
Let's Contribute
 
Advanced Computing for Sustainable Future
Advanced Computing for Sustainable FutureAdvanced Computing for Sustainable Future
Advanced Computing for Sustainable Future
 
Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries Ambidextrous Python - Introduction Python Libraries
Ambidextrous Python - Introduction Python Libraries
 
Faster Python
Faster PythonFaster Python
Faster Python
 
Startups and FOSS
Startups and FOSSStartups and FOSS
Startups and FOSS
 
How slow is Real slow - PyCon India 2013
How slow is Real slow - PyCon India 2013 How slow is Real slow - PyCon India 2013
How slow is Real slow - PyCon India 2013
 
Redis way of Anayltics with Python - Fifth Elephant 2012
Redis way of Anayltics with Python - Fifth Elephant 2012Redis way of Anayltics with Python - Fifth Elephant 2012
Redis way of Anayltics with Python - Fifth Elephant 2012
 
Building a Company atop of Open Source
Building a Company atop of Open SourceBuilding a Company atop of Open Source
Building a Company atop of Open Source
 
Pycon 2012 Scikit-Learn
Pycon 2012 Scikit-LearnPycon 2012 Scikit-Learn
Pycon 2012 Scikit-Learn
 
Test Driven Development in Python
Test Driven Development in PythonTest Driven Development in Python
Test Driven Development in Python
 

Último

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Thinking in Functions: Functional Programming in Python

  • 2. Agenda ★ Basics of Functional Programming ★ Functional Programming and Python ★ Everyday Functional Programming ★ Scaling with Functional Programming ★ Performance Implications ★ Data Explorations
  • 3. House rules ★ Show of hands please ★ Ask anytime - Raise your hands ★ Be hands on ★ Free to use online resources ★ One step at a time ★ No-one left out policy
  • 5. About Functional Programming ★ Formal Provability
  • 7. About Functional Programming ★ Ease of Debugging and Testing
  • 9. Basics of Functional Programming ★ Function as the atomic entity ○ First-class functions ○ Higher-order functions ○ Pure functions
  • 10. Basics of Functional Programming ★ Side Effects ○ Avoid state ○ Immutability
  • 11. Basics of Functional Programming ★ Lazy Evaluation
  • 13. Basics of Functional Programming ★ Recursion, Tail Recursion, Iterators, Currying, Sequences, pattern matching, monads....
  • 14. Myths of Functional Programming ★ It requires immutability/pureness ★ It requires an advanced type system ★ It is significantly less efficient ★ It makes you learn advanced math ★ You must give up all your imperative programming notions ★ Object orientation and functional paradigms are incompatible ★ Functional programs are easier to debug ★ Dynamic types are better than Static types
  • 15. Functional methodology in Python ★ itertools and functools ★ Decorators and Generators ★ What python CAN do ○ lazy eval, lambda, map, reduce, filter ★ What python CANNOT do (pragmatically) ○ Eg: Tail Recursion, Pure immutability, Pure Functions
  • 16. Functional Programming: Done everyday ★ map ★ reduce ★ filter ★ enumerate ★ iter ★ list comprehension ★ Generator Expressions ★ Generators ★ itertools ★ functools ★ operator ★ decorator ★ Lambda Functions
  • 17. List Comprehension data = [1,2,3,4,5] [item * 2 for item in data]
  • 18. Generator Expression data = [1,2,3,4,5] generator_exp = (i*i for i in data) sum(generator_exp)
  • 19. operator module import operator operator.add(40,2) operator.sub(45,3) data = {'company': 'Acme Corp.'} getCompany = operator.itemgetter('company') getCompany(data)
  • 20. enumerate for item in enumerate(['subject', 'verb', 'object']): print item
  • 21. map def upper(s): return s.upper() data = [“pycon”,”india”] map(upper, data)
  • 22. Map - Explained from urllib import urlopen urls = ['http://www.google.com', 'http://www.wikipedia.com', 'http://www.apple.com', 'http://www.python.org' ] result = [] for item in urls: result.append(urlopen(item)) return result def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a + b .... integers = [1, 2, 3, 4, 5] result = [] for item in integers: result.append(fib(item)) return result ?
  • 23. Map - Explained from urllib import urlopen urls = ['http://www.google.com', 'http://www.wikipedia.com', 'http://www.apple.com', 'http://www.python.org' ] result = [] for item in urls: result.append(urlopen(item)) return result def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a + b ... integers = [1, 2, 3, 4, 5] result = [] for item in integers: result.append(fib(item)) return result def map(function, sequence): result = [] for item in sequence: result.append(function(item)) return result html_texts = map(urlopen, urls) fib_integers = map(fib, integers)
  • 24. Lambda count_lambda =lambda w: len(w) print map(count_lambda, 'It is raining cats and dogs'.split()) #conditions in lambda lambda x: True if x % 2 == 0 else False
  • 25. reduce import operator data = ["PyCon", "India", "2015"] reduce(operator.concat, data)
  • 26. Reduce - Explained # Sum of a list of numbers def add(x, y): return x + y def sum(data): result = 0 for x in data: result = add(result, x) return result sum([5, 2, 3]) # Smallest in a list def lesser(x, y): if x < y: return x else: return y def min(data): result = 999999999999 for x in data: result = lesser(result, x) return result min([5, 2, 3]) ?
  • 27. Reduce - Explained # Sum of a list of numbers def add(x, y): return x + y def sum(data): result = 0 for x in data: result = add(result, x) return result sum([5, 2, 3]) # Smallest in a list def lesser(x, y): if x < y: return x else: return y def min(data): result = 999999999999 for x in data: result = lesser(result, x) return result min([5, 2, 3]) # Sum result = sum(data) result = reduce(add, data, 0) # Min result = min(data) result = reduce(lesser, data, 9999999999)
  • 28. filter def is_even(x): return (x % 2) == 0 filter(is_even, range(10)) #even better from itertools import ifilter filter_iterator = ifilter(is_even,data) filter_iterator.next()
  • 29. iter function numbers = [1,2,3] it = iter(numbers) # using while and StopIteration Exception try: while True: print it.next() except StopIteration: print "Complete" # as iterator in for loop it = iter(numbers) for value in it: print value
  • 31. itertools - chain it1 = iter([1, 2, 3]) it2 = iter([4, 5, 6]) itertools.chain(it1, it2)
  • 32. itertools - groupby city_list = [('Cochin', 'KL'), ('Bengaluru', 'KA'), ('Chennai', 'TN'), ('Mumbai', 'MH'), ('Trivandrum', 'KL'), ('Salem', 'TN'), ('Pune', 'MH')] for city, city_iterator in groupby(city_list, lambda x: x[0]): for city_state in city_iterator: print "%s is in %s." % (city, city_state[1])
  • 33. itertools - combinations, permutations import itertools itertools.permutations([1, 2, 3]) itertools.combinations([1, 2, 3, 4, 5], 2)
  • 34. itertools - izip dict(itertools.izip("ABCD", [1,2,3,4])) #OR zip("ABCD", [1,2,3,4])
  • 35. functools - partial import functools def log (message, subsystem): print '%s: %s' % (subsystem, message) server_log = functools.partial(log, subsystem='server') server_log('Unable to open socket')
  • 36. Decorators def p_decorate(func): def func_wrapper(name): return "Super %s" func (name) return func_wrapper @p_decorate def get_text(name): return "Hello %s" % name print get_text("John")
  • 37. Yield - creating custom generators data_list = ["Orange", "Microsoft", "Apple"] def one_at_a_time(data_list): for item in data_list: yield item one_at_a_time.next()
  • 38. Don't do unnecessary Classes class Greeting(object): def __init__(self, greeting="hello"): self.greeting = greeting def greet(self, name): return "{greeting} {name}!".format (greeting=greeting, name=name) hola = Greeting("hola") print hola.greet("bob") or ?
  • 39. Don't do unnecessary Classes class Greeting(object): def __init__(self, greeting="hello"): self.greeting = greeting def greet(self, name): return "{greeting} {name}!".format (greeting=greeting, name=name) hola = Greeting("hola") print hola.greet("bob") def greet(greeting, name): return "{greeting} {name}!".format(greeting=greeting, name=name) hello = functools.partial(greet, "Hello") hello("Dude") or
  • 40. The Bad Parts ★ Memory Inefficiencies ★ Purity ★ No Tail Recursion ★ Innately imperative (Guido) ★ Class based type system ★ Only imperative Error Handling (Exception) ★ Function Overloading ★ Mutable variables Python vs Functional
  • 41. Thinking about Scalability with Functions ★ map-reduce-filter - recipe for distributed computing ★ shared states- to be or not to be ★ immutable 'variables' ★ independent functions ★ Execution Pipelines - chained map-reduce
  • 42. Performance v/s Scalability ★ Functional Programs vs Object Oriented Programs ★ CPU intensive processes vs I/O intensive processes ★ The curse of GIL - workarounds ○ multiprocessing ★ Benchmarking ○ %timeit
  • 43. multiprocessing.Pool import multiprocessing def worker(): print 'Execute your function here' return if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start()
  • 44. // Why should I think in functions?
  • 45. why! ★ no side effects -no state, no deadlocks, no semaphores ★ automatic parallelization - unlimited scalability ★ composability - break down into smaller functions ★ Testing -independent functions; well defined arguments and return values ★ partial evaluation - pass around half baked functions instead of objects ★ elegant code -forces to write logically correct programs
  • 46. Hands On: Let’s do some Data Wrangling Blockbuster Database (http://www.crowdflower.com/data-for-everyone) ➢ Which genre has most movies? ➢ Which movie studio gross the most? ➢ Sort by most grossed and Highly rated movies demo code here
  • 47. Questions code samples in this presentation here atm@profoundis.com @atmb4u