Useful Patterns & Idioms Trent Nelson

Slides:



Advertisements
Similar presentations
CS 497C – Introduction to UNIX Lecture 5: Understanding the UNIX Command Chin-Chih Chang
Advertisements

C Language.
Objectives Understand grammar of OOP Understand equivalent Java code Discuss different implementations of classes and objects.
GoogleTest Primer. Outline Basic Concepts Assertions Basic Assertions Binary Comparison String Comparison Floating-Point Comparison Simple Tests Test.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lilian Blot TOWARDS MORE ADVANCED CONCEPTS & OBJECT ORIENTED PROGRAMMING Building Data Structure Autumn 2014 TPOP 1.
Lecture 2 Basics of C#. Members of a Class A field is a variable of any type that is declared directly in a class. Fields are members of their containing.
Lists Introduction to Computing Science and Programming I.
1 Software Testing and Quality Assurance Lecture 10 - The Testing Perspective (Chapter 2, A Practical Guide to Testing Object-Oriented Software)
Encapsulation by Subprograms and Type Definitions
Parameters, Arguments, Local Variables, and Scope CSC 1401: Introduction to Programming with Java Week 8 – Lecture 1 Wanda M. Kunkle.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
Python classes: new and old. New and classic classes  With Python 2.2, classes and instances come in two flavors: old and new  New classes cleaned up.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
COMP More About Classes Yi Hong May 22, 2015.
Introduction to Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
FPDS- NG Reports Overview December 16, Today’s Goals Provide an overview of the FPDS-NG reporting capability Demonstrate each of the reporting tools.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Recitation 2 Main Method, API & Packages, Java Basics.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 5 Decision Making.
Chapter 9: MuPAD Programming II Procedures MATLAB for Scientist and Engineers Using Symbolic Toolbox.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
CSE 413 Programming Languages & Implementation Hal Perkins Autumn 2012 Late binding and dynamic dispatch (Based on CSE 341 slides by Dan Grossman) 1.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 24 The String Section.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions.
Center for Software Sciences Northeastern University A domain specific language for Traversal Specification Johan Ovlinger Mitchell Wand Northeastern.
1 CSC241: Object Oriented Programming Lecture No 25.
Perl Chapter 6 Functions. Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function.
Finding a PersonBOS Finding a Person! Building an algorithm to search for existing people in a system Rahn Lieberman Manager Emdeon Corp (Emdeon.com)
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
1/33 Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Methods.
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Google C++ Testing Framework Part 2: Assertion. Concepts A test case contains one or many tests. ◦ You should group your tests into test cases that reflect.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Python C API overview References:
PIMPL Idiom Encapsulating Implementation. Forward Declaration Revisited forward class declaration – names the class, does not provide definition class.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Pyragen A PYTHON WRAPPER GENERATOR TO APPLICATION CORE LIBRARIES Fernando PEREIRA, Christian THEIS - HSE/RP EDMS tech note:
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Group Status Project Status.
Functions and Macros.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Lesson 06: Functions Class Chat: Attendance: Participation
Recursion Chapter 11.
Lecture 12: Message passing The Environment Model
CISC124 Assignment 3 sample solution will be posted tonight after 7pm.
Nate Brunelle Today: Functions
Python classes: new and old
Python classes: new and old
point when a program element is bound to a characteristic or property
CSE 190p University of Washington Michael Ernst
CISC101 Reminders Assignment 3 due today.
Nate Brunelle Today: Functions
Corresponds with Chapter 5
Using Modules.
Presentation transcript:

Useful Patterns & Idioms Trent Nelson

Overview  Initial experience learning decorators  My own crude explanation/definition  Some useful patterns/idioms

My Steps for Learning Decorators  Fired up Python Reference Manual  Look up ‘decorators’ in index  No hits  Search for ‘decorators’  Found PEP 318: Decorators for Functions and Methods  Nice bit of history  Doesn’t provide much in the way of education

My Steps for Learning Decorators (cont.)  Stumbled upon ‘definition’ of decorators in section 7.6 of the Python Reference Manual:  “A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion.”  Well then...

My Steps for Learning Decorators  Wouldn’t recommend this approach!  Surprisingly very little examples of how to actually write decorators in Python documentation  Had to google around to grok the concept  Would have preferred an explanation along the lines of...

Decorators: My Crude Explanation by Example  Consider the following, which demonstrates two different types of decorators (one that doesn’t take any arguments, and one that does): class def returns=c_char_p) def readSetting(self, setting):...  First important point: code body of your decorator will differ depending on whether or not you accept arguments

Decorator Without def cache(f): # f: function object of decorated method; has # useful info like f.func_name for the name of # the decorated method. def newf(*_args, **_kwds): # This code will be executed in lieu of the # method you've decorated. You can call the # decorated method via f(_args, _kwds).... return newf

Decorator Without  Define your decorator to accept one parameter, ‘f’  This will be the function object of the decorated method  Has useful info like f.func_name and f.f_frame  Define another method in the body, newf, that accepts the parameters *_args and **_kwds  Implement the body of your decorator in newf()  This will be called in lieu of the decorated method  Return newf at the end of your decorator def cache(f): # f: function object of decorated method; has # useful info like f.func_name for the name of # the decorated method. def newf(*_args, **_kwds): # This code will be executed in lieu of the # method you've decorated. You can call the # decorated method via f(_args, _kwds).... return newf

Decorator With returns=c_char_p) def dll(*args, **kwds): # args[0]: c_char_p # kwds['returns'] = c_char_p def decorator(f): # f: function object of decorated method; has # useful info like f.func_name for the name of # the decorated method. def newf(*_args, **_kwds): # This code will be executed in lieu of the # method you've decorated. You can call the # decorated method via f(_args, _kwds).... return newf return decorator

Decorator With returns=c_char_p)  Define your decorator as accepting two parameters, *args and **kwds  args[0]: c_char_p  kwds[‘returns’]: c_char_p  Define another method that takes a single parameter, ‘f’, which will be the function object of the decorated method  Define another method, newf, that accepts *_args, **_kwds  Implement the decorator body in newf  Return newf and decorator def dll(*args, **kwds): # args[0]: c_char_p # kwds['returns'] = c_char_p def decorator(f): # f: function object of decorated method; has # useful info like f.func_name for the name of # the decorated method. def newf(*_args, **_kwds): # This code will be executed in lieu of the # method you've decorated. You can call th # decorated method via f(_args, _kwds).... return newf return decorator

Summary  If you don’t accept arguments: def cache(f): def newf(*_args, **kwds):... return newf  If you do accept arguments: def dll(*args, **kwds): def decorator(f): def newf(*_args, **kwds):... return newf return decorator  To call the original (decorated method) in newf(): result = f(_args, _kwds)  Next up: useful idioms

Useful Idioms caching results of expensive operations casting return types to other objects simplifying interface to a C DLL via @db.selectAll: going too far?

Caching results of expensive  Definition: def cache(f): def newf(*_args, **_kwds): self = _args[0] cacheName = '_cache_' + f.func_name cache = self.__dict__.setdefault(cacheName, dict()) # Create a string representation of our decorated method's arguments to # use as the cache key. This ensures we only returned cached values for # method invocations with identical arguments. id = '%s,%s' % (repr(_args[1:]), repr(_kwds)) return cache.setdefault(id, f(*_args, **_kwds)) return newf  Sample usage: class def expensiveOperation(foo, bar, *args, **kwds):...

 See demo.

End of Presentation  Corresponding blog:   Questions?