Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python's Functional Tools

Avatar for Julian Gindi Julian Gindi
December 03, 2013

Python's Functional Tools

Advanced Python Magic

Avatar for Julian Gindi

Julian Gindi

December 03, 2013
Tweet

Other Decks in Programming

Transcript

  1. I’m Julian Gindi • Python developer at iStrategylabs (here) •

    (small-time) Python core contributor • github.com/juliangindi • @JulianGindi • JulianGindi.com • lebowski.juliangindi.com
  2. Python @isl • Django (content-heavy websites) • General scripting and

    internal tools • Fabric (executing commands on our servers) • Salt (provisioning our servers)
  3. Goals • Basic understanding of functional programming • Explain how

    it can help you craft simple, yet powerful code • Show you a couple practical applications of the functional paradigm
  4. Functional Programming (What) • First class functions. Higher-order functions •

    Pure functions • State • Immutable Data • Verbs instead of nouns
  5. Python? • Not a functional language in a “pure” sense

    • Multi paradigm language • Doesn't really matter - tools are still useful and awesome • Practical
  6. Why? • Downright awesome • Programs are easier to understand

    and debug • Often faster • Superior ability to deal with concurrency
  7. >>> my_tuple = ('A', 'B', ‘C’) >>> len(my_tuple) 3 >>>

    my_tuple.append('D') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append'
  8. Practical Features (Core) • Closures • Lambda’s • Iterators, generators

    • Partials • List Comprehension • Tuples • Built in functions (map, reduce, apply)
  9. # List Comprehensions 
 def square_list(items): new_list = [] new_list.append([x

    * x for x in items]) return new_list ! print square_list([1,2,3]) ! >> [1, 4, 9]
  10. # Closures ! def average_closure(a, b): def sum(): return a

    + b return sum() / 2 ! print average_closure(4, 4) ! >> 4
  11. import operator ! # Lambdas ! def weird_average(func, data) :

    return reduce(operator.add, map(func, data)) / len(data) ! print weird_average(lambda x: x * x , [1,2,3]) ! >> 4.66
  12. # Generators ! def fibonacci() : prev, current = 0,1

    while True : yield current prev, current = current, prev + current ! # Generator instantiation gen = fibonacci() ! # Generator usage for i in range(10) : print gen.next() ! >> 1 1 2 3 5 8 13 21 34 55
  13. # PARTIALS ! from functools import partial ! def power(x,y):

    return x ** y ! square = partial(power, y = 2) cube = partial(power, y = 3) ! assert (square(5), cube(7)) == (25, 343) ! ! !
  14. How to get started • ‘import functools’ • Create a

    simple program in a functional style • http://www.defmacro.org/ ramblings/fp.html - Functional programming for the rest of us • Execution in the Kingdom of Nouns