Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Simple metaprogramming with decorators


Python has a few built-in decorators that will modify a function or a method of a class. For example, in Chapter 11, Class Definitions, we saw @staticmethod and @property, which are used to alter the behavior of a method in a class. The @staticmethod decorator changes a function to work on the class instead of an instance of the class. The @property decorator makes evaluating a no-argument method available via the same syntax as an attribute.

A function decorator that's available in the functools module is @lru_cache. This modifies a function to add memoization. Having cached results can be a significant speed-up. It looks like this:

from functools import lru_cache
from glob import glob
import os

@lru_cache(100)
def find_source(directory):
    return glob(os.path.join(directory,"*.py"))

In this example, we've imported the @lru_cache decorator. We've also imported the glob.glob() function and the os module so that we can use os.path.join() to create filenames...