Book Image

Learning Python Design Patterns

By : Gennadiy Zlobin
Book Image

Learning Python Design Patterns

By: Gennadiy Zlobin

Overview of this book

<p>Design pattern is a well-known approach to solve some specific problems which each software developer comes across during his work. Design patterns capture higher-level constructs that commonly appear in programs. If you know how to implement the design pattern in one language, typically you will be able to port and use it in another object-oriented programming language.</p> <p>The choice of implementation language affects the use of design patterns. Naturally, some languages are more applicable for certain tasks than others. Each language has its own set of strengths and weaknesses. In this book, we introduce some of the better known design patterns in Python. You will learn when and how to use the design patterns, and implement a real-world example which you can run and examine by yourself.</p> <p>You will start with one of the most popular software architecture patterns which is the Model- View-Controller pattern. Then you will move on to learn about two creational design patterns which are Singleton and Factory, and two structural patterns which are Facade and Proxy. Finally, the book also explains three behavioural patterns which are Command, Observer, and Template.</p>
Table of Contents (14 chapters)
Learning Python Design Patterns
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Facades in Python's standard library


Facades can often be found in Python's source code.

The isdir function found in the os.path module serves as a Facade outshining work stat and os.stat modules. Internally isdir calls the os.stat function and that function in turn calls the stat() system call on the given path. This system call returns a structure with members, namely:

  • st_mode: This indicates some protection bits

  • st_size: This is the size of the file, in bytes

  • st_atime: This is the time of the most recent access

stat.S_ISDIR internally applies a bit mask S_IFMT to detect if the file passed by is actually a directory. This looks pretty confusing, but the good news is that the end user of this function does not need to know these intricacies. The user just needs to know about the isdir function.

def isdir(s):
  """Return true if the pathname refers to an existing directory."""
  try:
    st = os.stat(s)
  except os.error:
    return False
  return stat.S_ISDIR(st.st_mode)

Another example is...