Boilerplate to decorators via context managers in Python

SPEAKER BIOS

Patrick Morris

Mr. Morris is a member of the Portfolio Management Tools – Index Data team at BlackRock. Patrick’s service with BlackRock dates back to 2006, including his years with Barclays Global Investors (BGI), which merged with BlackRock in 2009. At BGI, he worked on the market data team responsible for the implementation and support of vendor feeds on the SUMS and ARIA platforms. Prior to joining BGI, Mr. Morris worked at Fotango (an online photo album and printing start up, owned by Canon) , Three X Communications (a logistics tracking company which was part of GE) and spent several years working as an astronomer at Durham University and Galway University.

MEETUP SUMMARY

On March, 9th, BlackRock hosted a Python meetup in London, which aimed at introducing some interesting Python features, such as decorators and context managers, and how they can be used to reduce boilerplate code. Our speaker for this event was Patrick Morris. He started the event by walking us through the piece of code being used for the demo, which basically performed three calculations on a list of numbers and a helper class with save/stop methods.

Then Patrick continued with explaining a little bit more about context managers, which can be used to allocate resources, e.g. opening and closing files, by showing us an example of how to open a file, read it and have it automatically close by a context manager. He further discussed how context managers can actually be created and more specifically – created with the help of decorators. The purpose of a decorator is to wrap functions within other functions, so that we can execute things before and after the functions, while having neater looking code. Patrick also demonstrated how to catch exceptions when calling the wrapped function and then re-raising them once we’re done.

The code from the presentation can be found here: https://github.com/atleypnorth/bp2dvcm

TECH-0047

BlackRock Engineering

Tags: