Python Dependency Injection



Similar documents
Design Patterns in Python

How To Design Your Code In Php (Php)

ios Design Patterns Jackie Myrose CSCI 5448 Fall 2012

Unit testing with mock code EuroPython 2004 Stefan Schwarzer p.1/25

Pyak47 - Performance Test Framework. Release 1.2.1

SPRING INTERVIEW QUESTIONS

Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1

CIS 192: Lecture 13 Scientific Computing and Unit Testing

XPoints: Extension Interfaces for Multilayered Applications

Threads and Processes

Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

Agile Software Development

Python for Rookies. Example Examination Paper

socketio Documentation

Android Application Development Course Program


Design Patterns. Design patterns are known solutions for common problems. Design patterns give us a system of names and ideas for common problems.

Python for Test Automation i. Python for Test Automation

Glossary of Object Oriented Terms

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Lecture 15: Inheritance

ABSTRACT FACTORY AND SINGLETON DESIGN PATTERNS TO CREATE DECORATOR PATTERN OBJECTS IN WEB APPLICATION

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Java EE Web Development Course Program

OOP? What is OOP? Why? OOP in a nutshell. Stéphane Ducasse 2.1

Services, Dependency Injection, and Containers, Oh my!

DESIGN PATTERN GENERATOR FOR PYTHON

Roulette: Inheritance Case Study

Project No. 2: Process Scheduling in Linux Submission due: April 28, 2014, 11:59pm

Building a Python Plugin

History OOP languages Year Language 1967 Simula Smalltalk

Computing Concepts with Java Essentials

Service-Oriented Architectures

Tes$ng Web Applica$ons. Willem Visser RW334

Introducing Tetra: An Educational Parallel Programming System

Android Developer Fundamental 1

SkyRecon Cryptographic Module (SCM)

Homework 2. A 4*4 image with 16 pixels Borders unaltered. Color of B2 = Average color of (B1,A2,B3,C2) A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 D1 D2 D3 D4

Things you didn't know about Python

When Security Gets in the Way. PenTesting Mobile Apps That Use Certificate Pinning

APScheduler Documentation

Apache Karaf in real life ApacheCon NA 2014

Web Frameworks. web development done right. Course of Web Technologies A.A. 2010/2011 Valerio Maggio, PhD Student Prof.

Lesson Plans Microsoft s Managing and Maintaining a Microsoft Windows Server 2003 Environment

Enterprise Ajax Security with ICEfaces

Advanced Customisation: Scripting EPrints. EPrints Training Course

How To Build An Online School Management System (Edsine)

ServiceNow ITSM Change History

Java on Guice Guice 1.0 User's Guide

Web development... the server side (of the force)

C++ INTERVIEW QUESTIONS

Don DeBolt and Kiran Bandla 29 September 2010

Test-as-a-Service and XenRT

Concepts and terminology in the Simula Programming Language

KIVY - A Framework for Natural User Interfaces

Name Spaces. Introduction into Python Python 5: Classes, Exceptions, Generators and more. Classes: Example. Classes: Briefest Introduction

Copyright 2013 wolfssl Inc. All rights reserved. 2

CIS 192: Lecture 10 Web Development with Flask

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

PHP Object Oriented Classes and objects

SaaS Attacks Happen: How Cloud Scale Changes the Security Game Sara Manning Dawson

Introduction to Logging. Application Logging

5. Advanced Object-Oriented Programming Language-Oriented Programming

Self-review 9.3 What is PyUnit? PyUnit is the unit testing framework that comes as standard issue with the Python system.

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Fundamentals of Java Programming

UOFL SHAREPOINT ADMINISTRATORS GUIDE

FTP Service Reference

The Phases of an Object-Oriented Application

Dependency Injection in ZF2. Rob Allen ~ October 2014

MatriXay Database Vulnerability Scanner V3.0

Best Practices for Programming Eclipse and OSGi

CReST: ToDo List Last Modified: 29 May 2012

Assurance in Service-Oriented Environments

Django Two-Factor Authentication Documentation

Software Testing with Python

Web CMS Forms. Contents. IT Training

SQL SERVER WITH PLEX: Strategies To Integrate PLEX With SQL Server A Symphony of Alternatives-

Host: INTRODUCTION TO SAP CRM WEB UI

The HTTP Plug-in. Table of contents

Understanding class paths in Java EE projects with Rational Application Developer Version 8.0

Software Testing. Theory and Practicalities

Design and Analysis of Content Management System Based on Factory Pattern

Aneka Dynamic Provisioning

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Best Practices in Qt Quick/QML. Langston Ball Senior Qt Developer ICS, Inc.

Chapter 13 - Inheritance

Python CS1 as Preparation for C++ CS2

Rahul Verma Chetan Giridhar

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Java SE 8 Programming

Wrestling with Python Unit testing. Warren Viant

61A Lecture 16. Friday, October 11

FTP Service Reference

JOURNAL OF OBJECT TECHNOLOGY

Testability of Dependency injection

Facebook Twitter YouTube Google Plus Website

(Unit) Testing ios Apps. Paweł Dudek

Getting Started with the Internet Communications Engine

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Transcription:

Python Dependency Injection Alex Martelli (aleax@google.com) http://www.aleax.it/yt_pydi.pdf Copyright 2008, Google Inc

The "levels" of this talk Shu ("Retain") Ha ("Detach") Py DP Ri ("Transcend") 2

The novice goes astray and says, "The Art failed me." The master goes astray and says, "I failed the Art." 3

Dependency Injection DP Name: "Dependency Injection" Forces: an object depends on other concrete objects which it instantiates (or accesses as singletons,...) we may want to control dependencies for all the usual good reasons in particular, unit-testing may require mocking otherwise-concrete objects we'll see examples & alternative solutions throughout the rest of this talk 4

A simple scheduler class ss(object): def init (self): self.i = itertools.count().next self.q = somemodule.priorityqueue() def AddEvent(self, when, c, *a, **k): self.q.push((when, self.i(), c, a, k)) def Run(self): while self.q: when, n, c, a, k = self.q.pop() time.sleep(when - time.time()) c(*a, **k) 5

(A "side note") class PriorityQueue(object): def init (self): self.l = [] def len (self): return len(self.l) def push(self, obj): heapq.heappush(self.l, obj) def pop(self): return heapq.heappop(self.l) 6

Fine, but......how do you test ss without long waits?...how do you integrate it with other subsystems' event loops/simulations? The core issue is that ss "concretely depends" on some specific objects (here, callables time.sleep and time.time). We'll discuss 3 approaches to solve this...: 1. the Template Method DP 2. "Monkey Patching" 3. the Dependency Injection DP 7

The Template Method DP One classic answer ("Template Method" DP):... when, n, c, a, k = self.q.pop() self.waitfor(when) c(*a, **k)... def WaitFor(self, when): time.sleep(when - time.time()) (to customize: subclass ss, override WaitFor) 8

TM DP example class sq(ss): def init (self): ss. init (self) ss.mtq = Queue.Queue() def WaitFor(self, when): try: while when>time.time(): c, a, k = self.mtq.get(true, time.time() - when) c(*a, **k) except Queue.Empty: return 9

Some issues with TM inheritance gives strong, inflexible coupling a customized-scheduler has complex, specialized extra logic far from ideal for either unit-testing or simulated-time system testing e.g.: if another subsystem makes a scheduler, how does it know to make a test-scheduler instance vs a simplescheduler one? (shades of recursion...) multiple integrations even harder than need be (but, there's no magic bullet for those!-) 10

Monkey-patching... import ss class faker(object): pass fake = faker() ss.time = fake fake.sleep =... fake.time =... extremely handy in emergencies, but......too often abused for NON-emergencies! "gives dynamic languages a bad name"!-) subtle, hidden "communication" via secret, obscure pathways (explicit is better!-) 11

The general DI idea class ss(object): def init (self, tm=time.time, sl=time.sleep): self.tm = tm self.sl = sl... self.sl(when - self.tm()) a known use: standard library sched module! 12

DI makes it easy to mock class faketime(object): def init (self, t=0.0): self.t = t def time(self): return self.t def sleep(self, t): self.t += t f = faketime() s = ss(f.time, f.sleep)... 13

DI/TM orthogonality Not at all mutually exclusive...: class ss(object): def init (self, tm=time.time, sl=time.sleep):... def WaitFor(self, when): self.sl(when-self.tm()) then may use either injection, or subclassing and overriding, (or both!-), for testing, integration, &c 14

DI design-choice details inject by constructor (as shown) with, or without, default dep. values? ensure just-made instance is consistent choose how "visible" to make the inject... inject by setter automatic in Python (use non-_ names) very flexible (sometimes too much;-) "inject by interface" (AKA "IoC type 1") not very relevant to Python DI: by code or by config-file/flags? 15

DI and factories class ts(object):... def Delegate(self, c, a, k): q = Queue.Queue() def f(): q.put(c(*a,**k)) t = threading.thread(target=f) t.start() return q each call to Delegate needs a new Queue and a new Thread; how do we DI these objects...? easy solution: inject factories for them! 16

DI and factories class ts(object): def init (self, q=queue.queue, t=threading.thread): self.q = q self.t = t... def Delegate(self, c, a, k): q = self.q()... t = self.t(target=f) pretty obvious/trivial solution when each class is a factory for its instances, of course;-) 17

Questions & Answers Q? A! 18