SlideShare a Scribd company logo
Object Orientation vs.  Functional Programming Writing Modular Python Programs Twitter: @insmallportions www.insmallportions.com
About Me
Modularity
Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python has good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other.
Object Orientation Class Oriented   The Three Pillars of OO are: Delegation Polymorphism Instantiation
Template Method class Game(object):     PLAYERS = 2     def initialize_game(self):         raise NotImplementedError()     def make_play(self, player):         raise NotImplementedError()     def end_of_game(self):         raise NotImplementedError()     def print_winner(self):         print self.current      def  play_game (self, players=PLAYERS):         self.initialize_game()         self.current = 0         while not self.end_of_game():             self.make_play(self.current)             self.current = (self.current + 1)\                 % players         self.print_winner() class Monopoly(Game):      PLAYERS = 4     def initialize_game(self):         pass # Monopoly code here     def make_play(self, player):         pass # Monopoly code here     def end_of_game(self):         pass # Monopoly code here     def print_winner(self):         pass # Monopoly code here  class Chess(Game):     def initialize_game(self):         pass # Chess code here     def make_play(self, player):         pass # Chess code here     def end_of_game(self):         pass # Chess code here
Abstract Base Classes >>> class MyDict(dict): ...   def __getitem__(self, key): ...       return 101 ...  >>> d = MyDict() >>> d['x'] 101 >>> d.get('x', 202) 202 >>>  >>> from collections import Mapping >>> class >>> from collections import Mapping >>> class MyMapping(Mapping): ...     def __getitem__(self, key): ...         return 101 ...  >>> m = MyMapping() Traceback (most recent call last):   File &quot;<stdin>&quot;, line 1, in <module> TypeError: Can't instantiate abstract class MyMapping with abstract methods __iter__, __len__
Mixins class XMPPClient(object):     def connect(self):         pass # XMPP code     def disconnect(self):         pass # XMPP code     def send(self, player):         pass # XMPP code     def terminate(self, player):         raise NotImplementedError()          def mainain_presence(self):         self.connect()         while not self.terminate():             yield         self.disconnect() class OnlineChess(Game,                 XMPPClient):     def initialize_game(self):         pass # Chess code here      ...     def end_of_game(self):         pass # Chess code here     def terminate(self, player):         return self.end_of_game()
Mixins (Multiple Inheritance) class A(object):     pass class B(A):     def method1(self):         pass class C(A):     def method1(self):         pass   class D(B, C):     pass
Wrapping/Composition Prefer Composition over Inheritance Use a class's functionality but not its API Expose only limited part of an object   Typical uses: Adapt Proxy Decorate
Wrapping/Composition class Eprom(object):     def read(self):         pass # Eprom code     def write(self, data):         pass # Eprom code     def complete(self):         pass # Eprom code class FileLikeEprom(object):     def __init__(self, eprom):         self._eprom = eprom     def read(self):         return self._eprom.read()     def write(self, data):         self._eprom.write(data)     def close(self):         self._eprom.complete() class SafeEprom(object):     def __init__(self, eprom):         self._eprom = eprom     def read(self):         return self._eprom.read()     def write(self, data):         if data.safe():              self._eprom.write(data)     def close(self):         self._eprom.complete()
Wrapping/Composition (Tricks) class FileLikeEprom(object):     def __init__(self, eprom):         self._eprom = eprom     def __getattr__(self, a):         if a == 'close':             return self.close         else:             return getattr(self._eprom, a)     def close(self):         self._eprom.complete() Don't Repeat Yourself Avoid boilerplate Use  __getattr__  to return computed attributes
Mixins Again class SafeAndFileLike(FileLikeEprom, SafeEprom):     def __init__(self, *args, **kwargs):         return super(SafeAndFileLike, self).__init__(*args, **kwargs)
Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other.
Functional Programming Functions take input and produce output, without any side effects. Pure functional languages are strict about side effect freeness. Python is not a pure functional language. Functions may be internally imperative, but appear purely functional in their behaviour.
Callbacks The Hollywood principle Role reversal, library code calls your code Library code accepts a callable and invokes it when appropriate   The main uses: Customisation Event Handling
sorted() sans Callbacks >>> people = [Person('John', 'Smith'), ...     Person('Mary', 'Doe'), ...     Person('Lucy', 'Pearl'),] >>> for p in sorted(people): ...     print p ...  Mary Doe Lucy Pearl John Smith >>>  class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     def __str__(self):         return '%s %s' % (self.f, self.s)     def __eq__(self, other):         return self.s == other.s     def __lt__(self, other):         return self.s < other.s
sorted() with Callbacks >>> for p in sorted(people, key=first_name): ...     print p ...  John Smith Lucy Pearl Mary Doe >>> for p in sorted(people, key=surname_name): ...     print p ...  Mary Doe Lucy Pearl John Smith >>>  class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     def __str__(self):         return '%s %s' % (self.f, self.s)   first_name = lambda p: p.f surname = lambda p: p.s
operator module from operator import attrgetter    class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     def __str__(self):         return '%s %s' % (self.f, self.s)   first_name = attrgetter('f') surname = attrgetter('s') attrgetter itemgetter add mul pow ...
Operations on aggregates  sum filter map reduce >>> def square(x): ...         return x ** 2 ...  >>> l = [1, 2, 3, 4, 5] >>> sum(map(square, l)) 55 >>> def square(x): ...        return x ** 2 ... >>> def odd(x): ...        return x % 2 ... >>> l = [1, 2, 3, 4, 5] >>> sum(map(square, filter(odd, l))) 35
itertools module cycle() repeat() chain() tee() product() ...
Decorators def cache(fn, c=None):      if c is None: c = {}     def cached(*args):         if args in c:             return c[args]         result = fn(*args)         c[args] = result         return result     return cached def adder(x, y):     return x + y   adder = cache(adder)  def cache(fn, c=None):      if c is None: c = {}     def cached(*args):         if args in c:             return c[args]         result = fn(*args)         c[args] = result         return result     return cached @cache def adder(x, y):     return x + y Do not write code like this, use: functools.lru_cache
Partial function evaluation >>> from functools import partial >>>  >>> def power(base, exp=1): ...         return base ** exp ...  >>> square = partial(power, exp=2) >>> cube = partial(power, exp=3) >>>  >>> l = [1, 2, 3, 4, 5] >>> sum(map(square, l)) 55 >>> print sum(map(cube, l)) 225
Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other.
Best of Both Worlds
Unbound methods Functions are descriptors Override binding behaviour Override differently for A.x and a.x Unbound methods know their class but not their instance Ideal for use in a functional style >>> food = ['Spam', 'ham', 'Cheese', 'eggs'] >>> sorted(food) ['Cheese', 'Spam', 'eggs', 'ham'] >>> sorted(food, key=str.lower) ['Cheese', 'eggs', 'ham', 'Spam'] >>>   >>> sorted(food, key='ham'.lower) Traceback (most recent call last):   File &quot;<stdin>&quot;, line 1, in <module> TypeError: lower() takes no arguments (1 given)
Computed fields (property) class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s      @property     def fullname(self):         return '%s %s' % (self.f,              self.s)   >>> p = Person('John', 'Smith') >>> p.fullname 'John Smith'  class Person(object):     def __init__(self, f, s):         self.f = f         self._s = s      @property     def s(self):         return self._s.upper()       @s.setter     def s(self, value):         self._s = value   >>> p = Person('Jane', 'Doe') >>> p.s 'DOE'  property([ fget [,  fset [,  fdel [,  doc ]]]])
property and inheritance class Person(object):     def __init__(self, t, f, s):         ...          def full(self):         return '%s %s' % (self.f,self.s)     fullname = property(full) class Customer(Person):     def full(self):         return '%s. %s %s' %                     (self.t, self.f, self.s)     >>> c = Customer('Mr', 'John', 'Smith') >>> c.fullname 'John Smith' class Person(object):      def __init__(self, t, f, s):         ...     def full(self):        return '%s %s' % (self.f, self.s)     def _full(self):         return self.full()     fullname = property(_full)   class Customer(Person):     def full(self):         return '%s. %s %s' %                        (self.t, self.f, self.s)   >>> c.fullname 'Mr John Smith'
Dependency Inversion  class Employee(object):     def __init__(self, f, s):         self.f = f         self.s = s     def register(self):         pass # Register me def register(emps):     for f, s in emps:         emp = Employee(f, s)         emp.register() >>> emps = [('John', 'Smith'), ('Mary', 'Doe')] >>>register(emps) def employee_fact(f, s):     return Employee(f, s) def register(emps, fact):     for f, s in emps:         emp = fact(f, s)         emp.register() >>> emps = [('John', 'Smith'), ('Mary', 'Doe')] >>>register(emps, employee_fact)
Python classes are factories class Employee(object):     def __init__(self, f, s):         self.f = f         self.s = s     def register(self):         pass # Register me def register(emps, fact):     for f, s in emps:         emp = fact(f, s)         emp.register() >>> emps = [('John', 'Smith'), ('Mary', 'Doe')] >>>register(emps, Employee) Python classes are callables Indistinguishable from other callables to the caller Allow us to postpone the creation of a factory until it actually needed
Many types of callables Functions Unbound methods Bound methods Classes Any object that has a  __call__  method is a callable Testable using the callable built-in function   >>> callable(str) True >>> callable('Spam') False >>>   class Callable(object):     def __init__(self, m):         self.message = m     def __call__(self):         print self.message class NotCallable(object):     def call(self):         print &quot;You Rang?&quot; >>> c = Callable('You Rang') >>> c() You Rang >>> n = NotCallable() >>> n() Traceback (most recent call last):   File &quot;<stdin>&quot;, line 1, in <module> TypeError: 'NotCallable' object is not callable
Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other nicely.
We hire superheroes! www.demonware.net/jobs/   Development & Operations Positions   Come talk to us

More Related Content

What's hot (20)

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
Eelco Visser
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
Eelco Visser
 
Antlr V3
Antlr V3Antlr V3
Antlr V3
guest5024494
 
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
Anoop Thomas Mathew
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
Eelco Visser
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
Nandan Sawant
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Alexis Gallagher
 
php string part 4
php string part 4php string part 4
php string part 4
monikadeshmane
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
Abdul Haseeb
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
Eelco Visser
 
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
Andreas Pauley
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
Phillip Trelford
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
Eelco Visser
 
Php basics
Php basicsPhp basics
Php basics
hamfu
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
Andres Almiray
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
Eelco Visser
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
Eelco Visser
 
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
Anoop Thomas Mathew
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
Eelco Visser
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
Nandan Sawant
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Alexis Gallagher
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
Abdul Haseeb
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
Eelco Visser
 
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
Andreas Pauley
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
Phillip Trelford
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
Eelco Visser
 
Php basics
Php basicsPhp basics
Php basics
hamfu
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 

Viewers also liked (11)

Pycon 2016
Pycon 2016Pycon 2016
Pycon 2016
Ashutosh Kumar Singh
 
Python idioms
Python idiomsPython idioms
Python idioms
Sofian Hadiwijaya
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Python Ireland - Who, how, what
Python Ireland - Who, how, whatPython Ireland - Who, how, what
Python Ireland - Who, how, what
Python Ireland
 
Async I/O in Python
Async I/O in PythonAsync I/O in Python
Async I/O in Python
Python Ireland
 
Python 温故
Python 温故Python 温故
Python 温故
勇浩 赖
 
Python for PHP developers
Python for PHP developersPython for PHP developers
Python for PHP developers
bennuttall
 
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Tom Lee
 
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland
 
Idioms and Idiomatic Expression
Idioms and Idiomatic ExpressionIdioms and Idiomatic Expression
Idioms and Idiomatic Expression
snsdilfany Exo
 
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
Tendayi Mawushe
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Python Ireland - Who, how, what
Python Ireland - Who, how, whatPython Ireland - Who, how, what
Python Ireland - Who, how, what
Python Ireland
 
Python for PHP developers
Python for PHP developersPython for PHP developers
Python for PHP developers
bennuttall
 
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Tom Lee
 
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland
 
Idioms and Idiomatic Expression
Idioms and Idiomatic ExpressionIdioms and Idiomatic Expression
Idioms and Idiomatic Expression
snsdilfany Exo
 
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
Tendayi Mawushe
 
Ad

Similar to Object Orientation vs. Functional Programming in Python (20)

Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Andrea Gangemi
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
jonycse
 
Python 3000
Python 3000Python 3000
Python 3000
Alexandro Colorado
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.
Mark Rees
 
Threading Is Not A Model
Threading Is Not A ModelThreading Is Not A Model
Threading Is Not A Model
guest2a5acfb
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
Ben James
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
georgebrock
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
Pythonic Math
Pythonic MathPythonic Math
Pythonic Math
Kirby Urner
 
The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python script
saniac
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
Andres Almiray
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Andrea Gangemi
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
jonycse
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.
Mark Rees
 
Threading Is Not A Model
Threading Is Not A ModelThreading Is Not A Model
Threading Is Not A Model
guest2a5acfb
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
Ben James
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
georgebrock
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python script
saniac
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
Andres Almiray
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Ad

More from Python Ireland (18)

What's the Scoop with Python 3?
What's the Scoop with Python 3?What's the Scoop with Python 3?
What's the Scoop with Python 3?
Python Ireland
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
Python Ireland
 
Introduction to Erlang for Python Programmers
Introduction to Erlang for Python ProgrammersIntroduction to Erlang for Python Programmers
Introduction to Erlang for Python Programmers
Python Ireland
 
Web-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using PythonWeb-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using Python
Python Ireland
 
Utopia Kingdoms scaling case. From 4 users to 50.000+
Utopia Kingdoms scaling case. From 4 users to 50.000+Utopia Kingdoms scaling case. From 4 users to 50.000+
Utopia Kingdoms scaling case. From 4 users to 50.000+
Python Ireland
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
Python Ireland
 
Python vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experiencePython vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experience
Python Ireland
 
Vim and Python
Vim and PythonVim and Python
Vim and Python
Python Ireland
 
Python Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - AppenginePython Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - Appengine
Python Ireland
 
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
Python Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with DjangoPython Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with Django
Python Ireland
 
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to PythonPython Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland
 
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and BoltsPython Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland
 
Lambada
LambadaLambada
Lambada
Python Ireland
 
Python for cloud computing
Python for cloud computingPython for cloud computing
Python for cloud computing
Python Ireland
 
IPython: The awesome python shell
IPython: The awesome python shellIPython: The awesome python shell
IPython: The awesome python shell
Python Ireland
 
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
Python Ireland
 
What's the Scoop with Python 3?
What's the Scoop with Python 3?What's the Scoop with Python 3?
What's the Scoop with Python 3?
Python Ireland
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
Python Ireland
 
Introduction to Erlang for Python Programmers
Introduction to Erlang for Python ProgrammersIntroduction to Erlang for Python Programmers
Introduction to Erlang for Python Programmers
Python Ireland
 
Web-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using PythonWeb-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using Python
Python Ireland
 
Utopia Kingdoms scaling case. From 4 users to 50.000+
Utopia Kingdoms scaling case. From 4 users to 50.000+Utopia Kingdoms scaling case. From 4 users to 50.000+
Utopia Kingdoms scaling case. From 4 users to 50.000+
Python Ireland
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
Python Ireland
 
Python vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experiencePython vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experience
Python Ireland
 
Python Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - AppenginePython Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - Appengine
Python Ireland
 
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
Python Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with DjangoPython Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with Django
Python Ireland
 
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to PythonPython Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland
 
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and BoltsPython Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland
 
Python for cloud computing
Python for cloud computingPython for cloud computing
Python for cloud computing
Python Ireland
 
IPython: The awesome python shell
IPython: The awesome python shellIPython: The awesome python shell
IPython: The awesome python shell
Python Ireland
 
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
Python Ireland
 

Recently uploaded (20)

Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 

Object Orientation vs. Functional Programming in Python

  • 1. Object Orientation vs. Functional Programming Writing Modular Python Programs Twitter: @insmallportions www.insmallportions.com
  • 4. Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python has good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other.
  • 5. Object Orientation Class Oriented   The Three Pillars of OO are: Delegation Polymorphism Instantiation
  • 6. Template Method class Game(object):     PLAYERS = 2     def initialize_game(self):         raise NotImplementedError()     def make_play(self, player):         raise NotImplementedError()     def end_of_game(self):         raise NotImplementedError()     def print_winner(self):         print self.current     def play_game (self, players=PLAYERS):         self.initialize_game()         self.current = 0         while not self.end_of_game():             self.make_play(self.current)             self.current = (self.current + 1)\                 % players         self.print_winner() class Monopoly(Game):     PLAYERS = 4     def initialize_game(self):         pass # Monopoly code here     def make_play(self, player):         pass # Monopoly code here     def end_of_game(self):         pass # Monopoly code here     def print_winner(self):         pass # Monopoly code here class Chess(Game):     def initialize_game(self):         pass # Chess code here     def make_play(self, player):         pass # Chess code here     def end_of_game(self):         pass # Chess code here
  • 7. Abstract Base Classes >>> class MyDict(dict): ...   def __getitem__(self, key): ...       return 101 ... >>> d = MyDict() >>> d['x'] 101 >>> d.get('x', 202) 202 >>>  >>> from collections import Mapping >>> class >>> from collections import Mapping >>> class MyMapping(Mapping): ...     def __getitem__(self, key): ...         return 101 ... >>> m = MyMapping() Traceback (most recent call last):   File &quot;<stdin>&quot;, line 1, in <module> TypeError: Can't instantiate abstract class MyMapping with abstract methods __iter__, __len__
  • 8. Mixins class XMPPClient(object):     def connect(self):         pass # XMPP code     def disconnect(self):         pass # XMPP code     def send(self, player):         pass # XMPP code     def terminate(self, player):         raise NotImplementedError()         def mainain_presence(self):         self.connect()         while not self.terminate():             yield         self.disconnect() class OnlineChess(Game,                 XMPPClient):     def initialize_game(self):         pass # Chess code here     ...     def end_of_game(self):         pass # Chess code here     def terminate(self, player):         return self.end_of_game()
  • 9. Mixins (Multiple Inheritance) class A(object):     pass class B(A):     def method1(self):         pass class C(A):     def method1(self):         pass   class D(B, C):     pass
  • 10. Wrapping/Composition Prefer Composition over Inheritance Use a class's functionality but not its API Expose only limited part of an object   Typical uses: Adapt Proxy Decorate
  • 11. Wrapping/Composition class Eprom(object):     def read(self):         pass # Eprom code     def write(self, data):         pass # Eprom code     def complete(self):         pass # Eprom code class FileLikeEprom(object):     def __init__(self, eprom):         self._eprom = eprom     def read(self):         return self._eprom.read()     def write(self, data):         self._eprom.write(data)     def close(self):         self._eprom.complete() class SafeEprom(object):     def __init__(self, eprom):         self._eprom = eprom     def read(self):         return self._eprom.read()     def write(self, data):         if data.safe():             self._eprom.write(data)     def close(self):         self._eprom.complete()
  • 12. Wrapping/Composition (Tricks) class FileLikeEprom(object):     def __init__(self, eprom):         self._eprom = eprom     def __getattr__(self, a):         if a == 'close':             return self.close         else:             return getattr(self._eprom, a)     def close(self):         self._eprom.complete() Don't Repeat Yourself Avoid boilerplate Use __getattr__ to return computed attributes
  • 13. Mixins Again class SafeAndFileLike(FileLikeEprom, SafeEprom):     def __init__(self, *args, **kwargs):         return super(SafeAndFileLike, self).__init__(*args, **kwargs)
  • 14. Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other.
  • 15. Functional Programming Functions take input and produce output, without any side effects. Pure functional languages are strict about side effect freeness. Python is not a pure functional language. Functions may be internally imperative, but appear purely functional in their behaviour.
  • 16. Callbacks The Hollywood principle Role reversal, library code calls your code Library code accepts a callable and invokes it when appropriate   The main uses: Customisation Event Handling
  • 17. sorted() sans Callbacks >>> people = [Person('John', 'Smith'), ...     Person('Mary', 'Doe'), ...     Person('Lucy', 'Pearl'),] >>> for p in sorted(people): ...     print p ... Mary Doe Lucy Pearl John Smith >>> class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     def __str__(self):         return '%s %s' % (self.f, self.s)     def __eq__(self, other):         return self.s == other.s     def __lt__(self, other):         return self.s < other.s
  • 18. sorted() with Callbacks >>> for p in sorted(people, key=first_name): ...     print p ... John Smith Lucy Pearl Mary Doe >>> for p in sorted(people, key=surname_name): ...     print p ... Mary Doe Lucy Pearl John Smith >>> class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     def __str__(self):         return '%s %s' % (self.f, self.s)   first_name = lambda p: p.f surname = lambda p: p.s
  • 19. operator module from operator import attrgetter   class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     def __str__(self):         return '%s %s' % (self.f, self.s)   first_name = attrgetter('f') surname = attrgetter('s') attrgetter itemgetter add mul pow ...
  • 20. Operations on aggregates sum filter map reduce >>> def square(x): ...         return x ** 2 ... >>> l = [1, 2, 3, 4, 5] >>> sum(map(square, l)) 55 >>> def square(x): ...        return x ** 2 ... >>> def odd(x): ...        return x % 2 ... >>> l = [1, 2, 3, 4, 5] >>> sum(map(square, filter(odd, l))) 35
  • 21. itertools module cycle() repeat() chain() tee() product() ...
  • 22. Decorators def cache(fn, c=None):     if c is None: c = {}     def cached(*args):         if args in c:             return c[args]         result = fn(*args)         c[args] = result         return result     return cached def adder(x, y):     return x + y   adder = cache(adder) def cache(fn, c=None):     if c is None: c = {}     def cached(*args):         if args in c:             return c[args]         result = fn(*args)         c[args] = result         return result     return cached @cache def adder(x, y):     return x + y Do not write code like this, use: functools.lru_cache
  • 23. Partial function evaluation >>> from functools import partial >>> >>> def power(base, exp=1): ...         return base ** exp ... >>> square = partial(power, exp=2) >>> cube = partial(power, exp=3) >>> >>> l = [1, 2, 3, 4, 5] >>> sum(map(square, l)) 55 >>> print sum(map(cube, l)) 225
  • 24. Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other.
  • 25. Best of Both Worlds
  • 26. Unbound methods Functions are descriptors Override binding behaviour Override differently for A.x and a.x Unbound methods know their class but not their instance Ideal for use in a functional style >>> food = ['Spam', 'ham', 'Cheese', 'eggs'] >>> sorted(food) ['Cheese', 'Spam', 'eggs', 'ham'] >>> sorted(food, key=str.lower) ['Cheese', 'eggs', 'ham', 'Spam'] >>>   >>> sorted(food, key='ham'.lower) Traceback (most recent call last):   File &quot;<stdin>&quot;, line 1, in <module> TypeError: lower() takes no arguments (1 given)
  • 27. Computed fields (property) class Person(object):     def __init__(self, f, s):         self.f = f         self.s = s     @property     def fullname(self):         return '%s %s' % (self.f,              self.s)   >>> p = Person('John', 'Smith') >>> p.fullname 'John Smith' class Person(object):     def __init__(self, f, s):         self.f = f         self._s = s     @property     def s(self):         return self._s.upper()      @s.setter     def s(self, value):         self._s = value   >>> p = Person('Jane', 'Doe') >>> p.s 'DOE' property([ fget [, fset [, fdel [, doc ]]]])
  • 28. property and inheritance class Person(object):     def __init__(self, t, f, s):         ...         def full(self):         return '%s %s' % (self.f,self.s)     fullname = property(full) class Customer(Person):     def full(self):         return '%s. %s %s' %                     (self.t, self.f, self.s)     >>> c = Customer('Mr', 'John', 'Smith') >>> c.fullname 'John Smith' class Person(object):      def __init__(self, t, f, s):         ...     def full(self):        return '%s %s' % (self.f, self.s)     def _full(self):         return self.full()     fullname = property(_full)   class Customer(Person):     def full(self):         return '%s. %s %s' %                        (self.t, self.f, self.s)   >>> c.fullname 'Mr John Smith'
  • 29. Dependency Inversion class Employee(object):     def __init__(self, f, s):         self.f = f         self.s = s     def register(self):         pass # Register me def register(emps):     for f, s in emps:         emp = Employee(f, s)         emp.register() >>> emps = [('John', 'Smith'), ('Mary', 'Doe')] >>>register(emps) def employee_fact(f, s):     return Employee(f, s) def register(emps, fact):     for f, s in emps:         emp = fact(f, s)         emp.register() >>> emps = [('John', 'Smith'), ('Mary', 'Doe')] >>>register(emps, employee_fact)
  • 30. Python classes are factories class Employee(object):     def __init__(self, f, s):         self.f = f         self.s = s     def register(self):         pass # Register me def register(emps, fact):     for f, s in emps:         emp = fact(f, s)         emp.register() >>> emps = [('John', 'Smith'), ('Mary', 'Doe')] >>>register(emps, Employee) Python classes are callables Indistinguishable from other callables to the caller Allow us to postpone the creation of a factory until it actually needed
  • 31. Many types of callables Functions Unbound methods Bound methods Classes Any object that has a __call__ method is a callable Testable using the callable built-in function   >>> callable(str) True >>> callable('Spam') False >>>  class Callable(object):     def __init__(self, m):         self.message = m     def __call__(self):         print self.message class NotCallable(object):     def call(self):         print &quot;You Rang?&quot; >>> c = Callable('You Rang') >>> c() You Rang >>> n = NotCallable() >>> n() Traceback (most recent call last):   File &quot;<stdin>&quot;, line 1, in <module> TypeError: 'NotCallable' object is not callable
  • 32. Roadmap Thesis Object Orientation is a proven way of creating models in software that represent the problem domain in a useful manner. There are many patterns that show how to achieve the modularity goal in different contexts. Antithesis Functional Programming is a long standing approach to defining processes in terms of others at different levels of abstraction. Higher order functions make the idiomatic ways to perform certain tasks fall out naturally. Synthesis Python good support for both styles of programming and for good reason. Depending on the situation one or the other maybe more appropriate. Moreover in Python these tools do not only exist but they complement each other nicely.
  • 33. We hire superheroes! www.demonware.net/jobs/   Development & Operations Positions   Come talk to us

Editor's Notes

  • #3: - Software Engineer at DemonWare - Online Services for some of the worlds most popular games, as well game online experiences like COD Elite - Python is one of our core technologies. - We&apos;re hiring!
  • #4: The sub-title of this talk is writing modular python programs. What do I mean by modularity and why do we want it? I don&apos;t want to make too much of a song and dance about it, because I think it is an obvious goal and programming languages have always been trying to help us achieve it. Never the less I think it is useful to at least loosely define it. We want the code we write to be individual components that do one job. That allows us to recombine those bits in different ways to solve new problems. We can build new stuff, making use of what we built before repeating ourselves as little as possible. To achieve this there are some properties our code needs to have. If there is an idea/concern we dealing with we would like that be expressed in as few places as possible ideally one. Conversely if we have a single module/class/method it would be better if it dealt with one concern rather than being cluttered with many different concerns. The diagrams on the screen try to illustrate this point. If each colour represents a particular concern we see that is scattered all over the place, if you were assigned the task of modifying the functionality represented by the yellow bits that would be a pretty annoying, grep helps but we would rather not be in that position in the first place. It is similarly problematic to have modules like we have on the left, in which lots of concerns are tangled together. One has to be aware of all the concerns in the module to change just one of them, or run the risk of inadvertently breaking other stuff that just happens to be near by. If you have ever had to say but I only changed the comments you know what I am talking about. Instead what we want is what we have on the right. Modules that related but separate, with each module dealing with a particular concern. If we can achieve that we can better reuse, re-purpose and extend our code to solve new problems. This is the open-closed principle ( should be open for extension, but closed for modification ). We should only modify a component when it&apos;s intrinsic behaviour changes, all other extension ideally should be made from the outside.   I think most modern programming languages provide features that help us achieve that goal. They succeed to varying degrees, we are going to look at some of the ways Python helps us do this.
  • #5: - I am not a classical rhetorician, but I aspire to play one on TV. The structure of classical rhetorical argument requires us to present the thesis, then explore the antithesis, and finally present the synthesis   - We are going take an example based approach, taking a look at a few Python OO and FP features that exemplify the point I am trying to make.   - Some of the examples themselves are taken mostly taken from the Python standard library, not so much the internals buy how we are supposed to use it. This is useful because the standard library (or any library for that matter) necessarily needs to extensible and reusable from the outside without modifying the library itself.
  • #6: Python OO, it is class oriented like most OO languages there are so exceptions that are prototype based a notable one being javascript, but are some others like self. - So OO is packaging state and behaviour generally to achive 3 things: 1. delegation which explicitly or implicitly passing on the responsibility of performing an action to somewhere else. implicit when you lookup an attribute: instance -&gt; class class -&gt; base classes explicit: delegating to another object that we have a reference to or even explicit delegation delegation to the object itself 2. Polymorphism allowing objects to act like other objects depending on the context. 3. Instantiation that is essentially having one blueprint that can be used to create many instances. - That is really all I am going to say about OO in general, I am kind of assuming we are all familiar with the basics of OO in Python.
  • #7: - base class offers &amp;quot;organizing method&amp;quot; which calls &amp;quot;hook methods&amp;quot; - in base class, most hook methods stay abstract - concrete subclasses implement the hooks - client code calls organizing method - A couple of things to note the Chess class does not specialise the winner printing; Data overriding something we cad do in python but not in many other languages   Mention how this structure would be hard to recreate with functions only, the obviousness of what is required is great.
  • #8: The methods on a dict do not necessarily call the methods you would expect. The reason for this is that python needs to protect the internal invariants of collections to prevent crashes. So the internal calling patterns are not obvious. ABC declare these constraints in an obvious way. This is really a variant of the template method design pattern with the sort of checks you would normally get in a staticly typed language. This still of course happens at runtime, but the failure is early, obvious and descriptive. Better still using an abc allows your code to move with the language. Because abc define the minimum set of the methods for each type. All other methods can be implemented in terms of these. You can override more methods to do things more efficiently, but if you don&apos;t things will still work.   The abc&apos;s really provide structured modularity and extendibility. We can extend them in ways that are sure to be consistent with intention of the base class.
  • #9: This can be thought of a form of the template method design pattern. Except the organising methods come from one or more base classes.   Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality. A class may inherit most or all of its functionality from one or more mixins through multiple inheritance .   Diamond problem: Python creates a list of a classes using the C3 linearization algorithm. That algorithm enforces two constraints: children precede their parents and if a class inherits from multiple classes, they are kept in the order specified in the tuple of base classes. Thus, the method resolution order is: D, B, C, A
  • #10: No discussion of multiple inheritance is complete without mentioning the &amp;quot;Diamon Problem&amp;quot;   The diamond problem such as it is, is In object-oriented programming languages with multiple inheritance and knowledge organization , the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C? A well designed language needs to have a deterministic resolution to this ambiguity. Python creates a list of a classes using the C3 linearization algorithm. That algorithm enforces two constraints: children precede their parents and if a class inherits from multiple classes, they are kept in the order specified in the tuple of base classes. Thus, the method resolution order is: D, B, C, A   Personally I think it is a mistake to rely on this order even it is deterministic. This situation can avoided in most cases just by taking care what you inherit from. Since the main reason for mixins is to get functionality defined in another class if inheritance is causing problems it may be time to consider composition instead.
  • #11: The design patterns literature. talks about preferring composition over inheritance. There is a good reason for this, for one thing inheritance always  expands the interface of the subclass with all of the parents attributes this may not always be what you want, especially if the base class is just a service that you may want to swap out in the in end. Inheritance cannot restrict it can only expand. This is a general mechanism but specific things you may be trying to achieve is to adapt or proxy some object. In all these cases though the general mechanism is the same. It is useful to distinguish between them (as is done in design patterns literature) to help in deciding when to apply the technique. However at the level of abstraction we are working today
  • #12: The design patterns literature. talks about preferring composition over inheritance. There is a good reason for this, for one thing inheritance always  expands the interface of the subclass with all of the parents attributes this may not always be what you want, especially if the base class is just a service that you may want to swap out in the in end. Inheritance cannot restrict it can only expand. This is a general mechanism but specific things you may be trying to achieve is to adapt or proxy some object. In this example say had a lot of code that knows how to deal with file like objects (perhaps it uses context lib closing()This is a way to reuse code in a context that it would not otherwise be usable, by creating a very thin wrapper.
  • #13: python def __getattr__(self, n) magic really make life easy for us, how does this help modularity well we only need to specify what we care about and the whole world making this a lot easier to change
  • #14: python def __getattr__(self, n) magic really make life easy for us, how does this help modularity well we only need to specify what we care about and the whole world making this a lot easier to change
  • #15: - I am not a classical rhetorician, but I aspire to play one on TV. The structure of classical rhetorical argument requires us to present the thesis, then explore the antithesis, and finally present the synthesis   - We are going take an example based approach, taking a look at a few Python OO and FP features that exemplify the point I am trying to make.   - The examples themselves are taken mostly taken from the Python standard library, not so much the internals buy how we are supposed to use it. This is useful because the standard library (or any library for that matter) necessarily needs to extensible and reusable from the outside without modifying the library itself.
  • #16: - In functional programming Functions are the primary means of abstraction. Programs are decomposed into a set of functions, that take some input and produce some output.   - Ideally a function should compute outputs from its inputs and do nothing else. That is takes values and produces new values. No mutable shareable state should be modified as the result of calling a function. Pure functional languages are strict about side effect freeness. (The type systems in such languages are used to control the limited amount of necessary side effects).   - This purity is what gives functional languages some of advantages you sometime here mentioned like provable program correctness. Also since side effects are limited or none existent, functional languages are very useful for concurrent programming.   - Python is not a pure functional language, because the language does permit side effects. Assignment of values to names which is not possible in pure functional languages is commonplace in Python program.    - Rather It is a language the supports functional style programming. The main thing that makes this possible is the fact that the language supports higher order functions (and other callables as we shall see later). That is functions are first class objects. So we can functions that accept other functions as inputs and even return functions as outputs.   - Never the less we can get pretty for with the less draconian functional support we have in python.
  • #17: One of the first examples most people encounter is programming python in a function style is callbacks. Before we take a look at some examples to make it more concrete let briefly discuss the concept of a callback. for: customization (flexibility)    &amp;quot;event-driven&amp;quot; architectures (&amp;quot;actual&amp;quot; events such as in GUI or network programming OR &amp;quot;pseudo&amp;quot; events for structuring of control-flow, a common example being a SAX XML parser.   This style of programming really begs for first class callables. The same effect can be achieved in other languages using interfaces, or functor objects or anonymous classes and so on, just to get around the lack of higher order functions.
  • #18: Mention how simple this is to achieve because we are not encumbered by unnecessary OO infrastructure.   Imagine create a subclass of list with different sorting, or subclasses of the objects you are comparing to implement __eq__ and __lt__, this would result in a combinatorial explosion of different subclasses to do sort by different combinations of fields.
  • #19: The sorted function is a higher order function, it accepts a function as its key argument and uses that key to customise how it does the sorting, that is rather than using the natural order of the class as defined by lt and eq.   Notice how much more flexible this is you can easily switch between sorting mechanisms. More importantly the users of the person class can easily sort this object in ways not envisaged by the creator of the class without having to modify or subclass the class itself. Remember our modularity goals, see how that fits in here? Some creates a class we can customise it behaviour from the outside.
  • #20: why write your own functions when all of pythons operators are available to you as functions itemgetter and attrgetter are examples of higher order functions, they return functions (or callables) as their results.   sorted requires a function that it can call we wrote a simple one for ourselves but this code was basically boilerplate that would have to be repeated. The operators in python can really be viewed as functions, they take operands (arguments) and produce results. There are many operators in Python which would be valuable viewed in this way.    The operator module does just that. The . operator is no execption and we can use it in our previous example. This is a higher order function its result is a function the extracts the field of the specified name from any object passed in. These and many more are available, they really come into their own in combination with what we are going to discuss in the next section.
  • #21: A powerful feature of functional programs is the ability to declare that we would like to do something to a set of objects, what is that something? Well we can pass that as an argument. This simple idea can lead to profound insights. Google MapReduce is inspired by this functional view of the world allow operations to be parallelzed then the result collated later. Since the operations on each object a separate this can be done transparently to the user. The process of iteration itself can be further customised through the use of filter. This may seem like a lot of trouble to go to just to iterate over a bunch of objects, but this pattern comes up so often that it is more than worth it.
  • #22: The idea of looping over a collection of objects and doing a customisable something to them is so fundamental to functional programming in python that there is whole module dedicated to that cause. It contains many useful variations on that theme. cycle() - infinitely cycle through an iterable repeat() - repeats an element a specified number of times chain()    - chains iterators together so they be iterated over as one sequnce groupby() - returns sub-iterators grouped by value of keyfunc(v) tee() - splits one iterator into n product() - cartesian product, equivalent to a nested for-loop
  • #23: Syntactic sugar for higher order functions. No real difference but the way the clearly indicate the intentions make it much much nicer to use higher order functions. I think it is fair to say that most peoples use of higher order functions in python is via decorators. Decorators really cause an explosion of this sort of higher order functions in the wild and of course the standard library has many useful decorators built in. Do not write code like this it is no only a bad caching decorator (that contains a memory leak), it is unnecessary since python 2.7 it is in the standard library.
  • #24: Allows you to define functions in terms of existing ones by freezing some of the arguments and keyword arguments. This avoids repetition of those parameters all over the code. This is another of the problems we discussed at the beginning, scattering the knowledge about a particular concern all over the code. This infact a rather more subtle version, it is not obvious in the heat of to see how having many function call for which a subset of the arguments must always be the same is modularity and maintenance problem. But thinking about it for a moment you can see that it really is.  functools partial allows you to avoid this without having to write trivial wrapper functions which people tend not to do anyway.   You may also here it referred to as currying , but if I call it currying people who really know about functional programming will come and beat me up because apparently currying is something different.
  • #25: - I am not a classical rhetorician, but I aspire to play one on TV. The structure of classical rhetorical argument requires us to present the thesis, then explore the antithesis, and finally present the synthesis   - We are going take an example based approach, taking a look at a few Python OO and FP features that exemplify the point I am trying to make.   - The examples themselves are taken mostly taken from the Python standard library, not so much the internals buy how we are supposed to use it. This is useful because the standard library (or any library for that matter) necessarily needs to extensible and reusable from the outside without modifying the library itself.
  • #26: We have seen how python&apos;s oo features allow us to express well the structural relationships between object and better communicate the constraints we want to impose as in the abc example. We have also seen how the functional approach makes it easy to express performing different operations over a given set of objects and how higher order functions allow us to easily customise those operations.   I could end the talk right here and legitimately claim that I have shown what I set to. However the story only gets better from here the OO and functional aspects of python are not separate worlds that are not intended to meet. Quite the contrary in Python the two approaches complement each other nicely. We are now approaching our foreshadowed conclusion that the design of Python takes both the OO and functional view into account. This section contains a selection of examples that demonstrate this multi-paradigm  approach to programming that Python supports and how it allows for really clean solutions.
  • #27: The functional style of programming relies heavily on passing functions around, than applying them to objects later (using itertools or some of the other callback we talked about previously. Functions are descriptors Override binding behaviour Override differently for A.x and a.x Unbound methods know their class but not their instance Ideal for use in functional scenarios where the target object is specified directly.
  • #28: Using the property higher order function to bring new functionality in an OO context. Avoids the unnecessary getter setter desease in Java other languages. C# does infact have properties because it is designed by Anders so has influence from Delphi The decorators are just sugar for the property higher order function.
  • #29: property and inheritance there is an unintentional pun there.   Property results in early binding. The property has a handle to the specific function object passed into it when it was created. It cannot know about the methods in the derived class. We talked about python helping smooth the impedance mismatch between OO and FP well this is a case where the abstraction leaks a bit. Luckily the fix is not that complicated. A layer of indirection solved every problem in computer science. I do not think that is quite true it solves many problems though and this is one of them.
  • #30: Do not scatter dependencies on specific classed throughout your  code this makes it harder to change implementations down the line    I know what you thinking I can use grep,    but if you now need to do some checking and perhaps initialise the object a little differently based on some previously on unforeseen factors this is now going to be much more of a pain. Invert the dependency, use a factory instead. Of course we all do this every time we are instantiating a class right. Modularity again we want to be able to change things in future without too much pain.
  • #31: What I really mean is that python classes are callables. Python classes are callables, like functions and methods Indistinguishable from other callables to the caller, for the most part of course via introspection you can tell the difference but in typical cases they are the same Allow us to postpone the creation of a factory until it actually needed. this is similar to how property
  • #32: One of the reasons python is so suitable for programming in a functional style is that there are several different types of callables, which are mostly inter changeable. Notice how the documentation for what I have been calling higher order functions, in the operator module such as itemgetter attrgetter and method caller say they return callables not functions. If they are not functions what else could they be? Class based callables can be handy if you want a callable that has internal state that is uses when called.
  • #33: - I am not a classical rhetorician, but I aspire to play one on TV. The structure of classical rhetorical argument requires us to present the thesis, then explore the antithesis, and finally present the synthesis   - We are going take an example based approach, taking a look at a few Python OO and FP features that exemplify the point I am trying to make.   - The examples themselves are taken mostly taken from the Python standard library, not so much the internals buy how we are supposed to use it. This is useful because the standard library (or any library for that matter) necessarily needs to extensible and reusable from the outside without modifying the library itself.