Book Image

The Python Apprentice

By : Robert Smallshire, Austin Bingham
Book Image

The Python Apprentice

By: Robert Smallshire, Austin Bingham

Overview of this book

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it’s not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.
Table of Contents (21 chapters)
Title Page
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
12
Afterword – Just the Beginning

Clean-up actions


Sometimes you need to perform a clean-up action irrespective of whether an operation succeeds. In a later module we'll introduce context managers which are the modern solution to this common situation, but here we'll introduce the tryfinally construct, since creating a context manager can be overkill in simple cases. In any case, an understanding of tryfinally is useful for making your own context managers.

Consider this function, which uses various facilities of the standard library os module to change the current working directory, create a new directory at that location, and then restore the original working directory:

import os

def make_at(path, dir_name):
    original_path = os.getcwd()
    os.chdir(path)
    os.mkdir(dir_name)
    os.chdir(original_path)

At first sight this seems reasonable, but should the call to os.mkdir() fail for some reason the current working directory of the Python process won't be restored to it's original value, and the make_at() function...