Case study

Let's try to tie everything we've learned together with a larger example. We'll be designing a simple real estate application that allows an agent to manage properties available for purchase or rent. There will be two types of properties apartments and houses. The agent needs to be able to enter a few relevant details about new properties, list all currently available properties, and mark a property as sold or rented. For brevity, we won't worry about editing property details or reactivating a...

Exception hierarchy

We've already encountered many of the most common built-in exceptions, and you'll probably encounter the rest over the course of your regular Python development. As we noticed above, most exceptions are subclasses of the Exception class. But this is not true of all exceptions. Exception itself actually inherits from a class called BaseException (In fact, all exceptions must extend the BaseException class or one of its subclasses). There are two key exceptions, SystemExit and KeyboardInterrupt,...

Functions are objects too

Programming languages that over-emphasize object-oriented principles tend to frown on functions that are not methods. In such languages, you're expected to create an object to sort of wrap the single method involved. There are numerous situations where we'd like to pass around a small object that is simply called to perform an action. This is most frequently done in event-driven programming, such as graphical toolkits or asynchronous servers we'll see some design patterns that use it in the...

Handling exceptions

Now let's look at the tail side of the exception coin. Namely, if we encounter an exception situation, how should our code react to, or recover from it We handle exceptions by wrapping any code that might throw one (whether it is exception code itself, or a call to any function or method that may have an exception raised inside it) inside a try except clause. The most basic syntax looks like this print(I caught an exception) print(executed after the exception) If we run this simple script using...

Modules and packages

Now that we know how to create classes and instantiate objects, it is time to think about organizing them. For small programs, we can just put all our classes into one file and put some code at the end of the file to start them interacting. However, as our projects grow, it can become difficult to find one class that needs to be edited among the many classes we've defined. This is where modules come in. Modules are simply Python files, nothing more. The single file in our small program is a...

Variable argument lists

Default values alone do not allow us all the flexible benefits of method overloading. The thing that makes Python really slick is the ability to write methods that accept an arbitrary number of positional or keyword arguments without explicitly naming them. We can also pass arbitrary lists and dictionaries into such functions. For example, a function to accept a link or list of links and download the web pages could use such variadic arguments, or varargs. Instead of accepting a single value...

Who can access my data

Most object-oriented programming languages have a concept of access control. This is related to abstraction. Some attributes and methods on an object are marked private, meaning only that object can access them. Others are marked protected, meaning only that class and any subclasses have access. The rest are public, meaning any other object is allowed to access them. Python doesn't do that. Python doesn't really believe in enforcing laws that might someday get in your way. Instead, it provides...

Composition and inheritance

So far, we've learned to design systems as a group of interacting objects, where each interaction is viewing the objects involved at an appropriate level of abstraction. But we don't know yet how to create those levels of abstraction. There are a variety of ways to do this we'll discuss some advanced design patterns in Chapter 8 and Chapter 9. But even most design patterns rely on two basic principles known as composition and inheritance. Composition is the act of collecting together several...

A completely different way to set up variables

One of the most common uses for the various setup and teardown functions is to ensure certain class or module variables are available with a known value before each test method is run. py.test offers a completely different way to do this using what are known as funcargs, short for function arguments. Funcargs are basically named variables that are previously set up in a test configuration file. This allows us to separate configuration from execution of tests, and allows the funcargs to be used...

Testing with pytest

The Python unittest module is very verbose and requires a lot of boilerplate code to set up and initialize tests. It is based on the very popular JUnit testing framework for Java. It even uses the same method names you may have noticed they don't conform to the PEP-8 naming standard, which suggests underscores be used to separate words in a method name, rather than CamelCase and test layout. While this is effective for testing in Java, it's not necessarily the best design for Python testing....

Jinja Templating

Now, we can set up Jinja to serve some templates from a folder for us Well that was easy. This gives us a templates variable that we can use to load templates based on filename from the given folder. Before we create the CherryPy app server, let's have a look at the templates. Let's scrutinize the simple template for adding a blog article first block title New Entry endblock block content form method POST Title lt input name title type text size 40 gt lt br gt lt textarea name message rows 10...

Command pattern

The command pattern adds a level of abstraction between actions that must be done, and the object that invokes those actions, normally at a later time. In the command pattern, client code creates a Command object that can be executed at a later date. This object knows about a receiver object that manages its own internal state when the command is executed on it. The Command object implements a specific interface typically it has an execute or do_action method, and also keeps track of any...

String formatting

Python 3 has a versatile string formatting mechanism that allows us to easily construct strings comprised of hard-coded text and interspersed variables. We've used it in many previous examples, but it is much more versatile than the simple formatting specifiers we've used. Any string can be turned into a format string by calling the format method on it. This method returns a new string where specific characters in the input string have been replaced with values provided in the arguments and...

Python Design Pattern Command Object

Absolute imports 46 abstract factory pattern about 271 examples 272 implementing 273-275 UML class diagram 272 abstraction 16 access control 50, 51 adapter pattern about 257, 259 benefits 258 structure 258 UML diagram 258 add_child method 279 add_point method 127 Agent class 90 aggregation 19 all method 352 API SQLite 348 append method 170 append method 98 anchor 356 expand 356 fill 356 ipadx 356 ipady 356 padx 356 pady 356 side 357 assertDictEqual method 320 assertEqual method 318 assertFalse...

CherryPy

CherryPy version 3.2 is the first major web application server to be made available on the Python 3 platform. It can be downloaded from http cherrypy.org . It is not a full-stack framework like the very popular Django, TurboGears, or Zope libraries. These frameworks provide extra support for data storage, templating, authentication, and other common web operations. Such features are not impossible in CherryPy, you re just responsible for finding or implementing them yourself. CherryPy is a very...