OBJECTIVES

  • Introduce the concept of separation of concerns.
  • Discuss how scope can control access to information.
  • Show how modules can:
    • form the main organisational unit of a complex program;
    • facilitate reuse;
    • provide interfaces and achieve information hiding.
  • Show how packages can add additional levels of organisation.
  • Explore good practices for your solution’s structure.

RECAP

People who design aircraft carriers understand how to build modular systems… when the toilet on an aircraft carrier gets clogged, it doesn’t start firing missiles. That’s because the toilet system and the missile system are separated very much.

(Tanenbaum, 2010)

Chapter 3 examined decomposition, a method that breaks a problem down into smaller pieces that can each be solved individually. It was pointed out that a number of patterns appear time and again in solutions, so often in fact that those patterns form the building blocks of any typical programming language, Python included. You should by now be familiar with some of the basic types of building blocks, including:

  • instructions (that is, statements and expressions);
  • conditionals;
  • loops;
  • subroutines (that is, functions).

For very small programs – a few dozen lines at the most – these building blocks serve sufficiently well. However, as programs increase in size, you need better ways of organising your code. Just as you can’t use the same techniques required to build a kennel as you would to build a skyscraper, you need additional techniques to build large programs. Complex solutions require you to organise your smaller pieces into larger, more manageable parts.

This chapter shows you the techniques on offer and how to apply them in Python. In each case, we’ll use the example from Chapter 3 (which showed how to build a complex image out of a collection of simple shapes) to demonstrate the technique.

images

The image drawing example was introduced in Chapter 3 ; see ‘Patterns and generalisation’.

INTRODUCING TKINTER

So far, our programs have been exclusively text-based. Such programs are easy to write because you only need to use the print statement to make your program display things. However, making your programs display graphics adds a whole new level of complexity. Thankfully, other people have created solutions that you can use to make drawing graphics easier.

The solution we will use in this chapter to draw things is called tkinter. This is a standard, built-in module you can use to draw graphics as part of your program. It provides a collection of functions that allow you to draw various objects onto a canvas.

To use tkinter yourself, here’s some of the basics. First, we need to get access to the functions in tkinter by importing the module. (Importing modules is discussed in detail later in this chapter.) This code achieves that:

import tkinter

Then, we need to create a main window where our graphics will be displayed:

window = tkinter.Tk ()

Next, we need to add a canvas to our window, onto which we can draw things:

c = tkinter.Canvas(window)

Finally, we then command the window to display what we’ve done. This is done by telling the canvas to put all the objects we created in place (via a function called pack) and telling the window to display itself (via a function called mainloop):

c.pack()
window.mainloop()

And that’s it. This is essentially startup code. Running it will display a window like this:

Screenshot: A Tkinter G U I window with no visible elements or content.

Of course, the window is empty because we didn’t actually add anything yet, but we’ll get to that shortly. After creating the window and canvas (but before making them display themselves), we then need to draw all our objects.

In summary, every code sample in this chapter assumes that you have already added the startup code like this:

import tkinter

window = tkinter.Tk ()
c = tkinter.Canvas(window)

# Code for drawing objects goes here…

c.pack()
window.mainloop()

SEPARATING CONCERNS

This section introduces the idea of separating out the various different concerns of your program into sensible parts.

images

Concern: a single aspect of carrying out a solution. In a spreadsheet, for example, calculating the contents of a cell and displaying a cell on the screen are two different concerns.

Example (part 1)

Let’s start by breaking down the image of a face into a series of simple shapes. We’ll use:

  • one large circle for the face outline;
  • a pair of concentric circles (the inner one filled) for each eye;
  • a line for a mouth.

We’ll also distinguish between drawing and rendering.

  • Rendering describes a multi-step process involved in progressively building up a representation.
  • Drawing describes the action of actually making something appear on the screen.

Chapter 3 demonstrated a way to construct an algorithm for drawing a simple face, an example of which looks like this:

  1. Draw circle with radius 30 at position 50,50.
  2. Draw circle with radius 10 at position 70,70.
  3. Draw circle with radius 5 at position 70,70 filled black.
  4. Draw circle with radius 10 at position 100,70.
  5. Draw circle with radius 5 at position 100,70 filled black.
  6. Draw line from 70,110 to 100,100.

Here’s our first attempt at turning that algorithm into a Python program that renders a face. Let’s just look at the first step for a moment:

# Function: create_oval(x1, y1, x2, y2)
# Tells the canvas to draw an oval whose left
# is at position x1, top is at position y1,
# right is at position x2, and bottom is at y2.
c.create_oval(50, 50, 120, 120)

This raises the issue of a coordinate system. A canvas is divided up into pieces like a piece of graph paper. Each resultant square has a position (i.e. a coordinate) of the form (x, y). The top left-most coordinate is (0, 0). As you move right, the x-coordinate increases, so jumping five steps to the right lands you at coordinate (5, 0). As you move down, the y-coordinates increase, so jumping ten steps down from the top left would land you at (0, 10).

Since the example above draws an oval whose width and height are equal, the result is a circle. This will serve as the outline of the face.

Drawing the eyes works much the same. They’re simply smaller and positioned inside the larger circle.

c.create_oval(60, 60, 80, 80)
c.create_oval(90, 60, 110, 80)

We’ve just created the outline of the eyes, so now let’s add some black pupils. The create_oval function allows you to optionally fill in the oval you create with a colour like so:

c.create_oval(65, 65, 75, 75, fill=’black’)
c.create_oval(95, 65, 105, 75, fill=’black’)

Finally, let’s give our face a flat, neutral mouth by drawing a line.

# Function: create_line(x1, y1, x2, y2)
# Draws a line from position (x1,y1) to (x2,y2)
c.create_line(70, 110, 100, 110)

Let’s put it all together inside a function which we can call whenever we want to draw a face.

images

Running this function (don’t forget to include the startup code we wrote earlier!) results in a window looking something like this:

Tkinter Window Neutral Face: A Tkinter G U I window displaying a neutral face with circular eyes and a straight-line mouth.

Let’s extend our solution so it can also draw a smiley face.

images

Tkinter Window Happy Face: A Tkinter G U I window displaying a happy face with circular eyes and a smiling mouth.

The principle behind separation of concerns

All the steps in the previous example could have been put into just one function called render_faces . However, that would have resulted in mixing up concerns, meaning it wouldn’t have been possible to separate the idea of rendering a neutral face from the idea of rendering a smiley face. Instead the solution follows the principle of separation of concerns . It has a pair of functions that each have a single concern – rendering one image – allowing you to choose between them.

Separating pieces of functionality into independent units increases the flexibility of your solution. It’s a way of implementing all those patterns you discovered after having broken down the original problem. A function is Python’s most basic means of allowing you to create an independent block of code that carries out (ideally) a single, well-defined task within your solution. When functions have just one concern each, it’s easier to take advantage of patterns and combine them in creative ways.

A function that performs several tasks is also harder to both reuse and test. By making each function focus on a single, well-defined task:

  • Each function becomes more reusable – in the above example, someone using these functions can choose between a smiley face or a neutral face.
  • Each function is more testable – it’s easier to localise a problem in the solution because you can test smaller pieces.

Example (part 2)

Strictly speaking each function in the example still has, not one, but two concerns: rendering images (that is, breaking down the complex image into steps) and drawing shapes. You might question the latter concern. Surely, tkinter is the one doing the drawing? Yes and no. It’s true that tkinter does the drawing work, but the rendering functions are overly (and needlessly) concerned with how those shapes are drawn.

To see the problem, imagine that at some point in the future you’re asked to replace the tkinter with a sexy, new-and-improved drawing module ( ultra_draw ). That would mean making a lot of changes to the existing code: every single line that referred to tkinter would need altering.

To cut down on the potential work, we could separate these concerns strictly: the rendering functions should focus only on rendering (which was described as a multi-step process that progressively builds up a representation) and we should move the drawing work into new separate functions:

images

The rendering functions now know a lot less about how the drawing is done, and that’s good . Instead of controlling the drawing work themselves directly, the rendering functions delegate the work to the new functions, draw_line and draw_oval .

Of course, the new functions need some information to work with, namely the positions and dimensions of the shapes being drawn. The rendering functions pass these to the drawing functions via parameters.

DEFINING INFORMATION SCOPE

As well as separation of concerns, the previous example also teaches us something about scope. When you look at the code, you’ll notice that each rendering function calls a drawing function several times. Each time it does so, it passes some values to the drawing function, which in turn, creates some new variables for those values (like x1 or y1 ). After a drawing function completes its work, it destroys those variables before passing control back to a rendering function.

Technically this means that variables are being created and destroyed continually throughout execution of this solution. Phrased like this, it sounds as though a lot of extraneous work is being carried out. Why not just create each variable once and allow all functions to refer to them or update them whenever they wish?

Technically, that is possible. Variables that behave like that are called global variables and are created by defining them at the top level of the program. A variant of the previous solution that uses global variables would look like this:

images

However, global variables are a notorious source of errors because their values are subject to being changed at any time in any number of ways. In fact, there’s a deliberate mistake in this example - can you spot it before running the program?

When you run the program, the image looks like this:

Tkinter Window Winking Face: A Tkinter G U I window showing a winking face with one circular eye, one closed eye, and a straight-line mouth.

What went wrong? After drawing the left eye, the colour variable kept its old value of ‘black’. That meant, when drawing the outside of the right eye, the program drew a black circle. To fix this mistake, you would need to add the instruction colour = None after drawing the left eye but before calling draw_oval() for the right eye.

This means a global variable’s state must be tracked across a potentially huge number of lines of code. The bigger your program, the harder it becomes.

Experience shows that the availability of information should be strictly limited. By ensuring that functions have access only to objects that they must have, we can avoid the kinds of problems just described. Scoping helps us to achieve this.

Principles behind scope

An object’s scope refers to the ‘area’ of a program in which that object may be referenced. When you create an object in a certain area of a program, that object can only be referred to by instructions within the same area. That area is the object’s scope.

For a simple linear program without any functions, this means that an object can be used anywhere in the same program.

file1.py

# Executing print(my_number) before the following line
# would result in an error.
my_number = 1

# Now my_number exists and you can use it.
print(my_number)

However, if you then wrote a second program in another file that referred to my_number , like this:

file2.py

print(my_number)

an error would occur. That’s because the scope of my_number is limited to the first program and the second program can’t see it.

Whenever you create an object, you’re implicitly giving it a scope. By default, an object’s scope is limited to the area in which it is defined. This results in several levels of scope. For the moment, we’ll discuss just two of them: global and local:

  • Global objects are defined at the ‘top level’ of a program and can be accessed from anywhere in the same module. my_number was a global object.
  • Local objects are defined inside of a function and can only be referenced from within the same function.

In this example:

images

x is a global object.

In this example:

images

msg is a local object and its scope is limited to the create_message function. That’s why you can refer to it from inside the function, but not from outside. As seen in an earlier example, it’s possible for functions to reference globally scoped objects, so long as you identify them using the global keyword (for example, by adding the line global msg at the beginning of create_message ).

Scoping variables lets you avoid the headaches that come with the use of global variables. When collaborating functions need to share information, they should do so via parameter passing, as shown in the next section.

Example (part 3)

The full version of our solution using locally scoped variables looks like this:

images

USING MODULES

Plans are afoot for the image rendering solution. It is to become a full-blown library of subroutines for drawing emojis. Eventually it will be full of functions that draw a diverse range of little images – not just faces, but weather icons, vehicles, emotional symbols and lots more.

How could we expand the current solution to realise this? We could keep adding a new rendering function for each additional image. However, dozens of new images are planned and that would mean dozens of functions being added to our current module. As a result, it would become very long and unwieldy.

Instead, we’ll break up our solution into modules.

Principle behind modules

images

Decomposition was discussed in Chapter 3 .

After problem decomposition, your solution will be arranged into a hierarchy of pieces. The broadly phrased goal of the solution sits at the top of the hierarchy. Along the bottom will be a collection of small pieces that each focus on solving one tiny sub-problem. These pieces at the lowest level are ideal candidates for becoming functions in your program, because a function should also be small and focus on doing just one small task (see Figure 9.1 ).

Figure 9.1 Example partial hierarchy of the emoji drawing problem

Flowchart: A hierarchical flowchart for drawing emoji icons, starting with Draw emoji icons. Branches include Break into shapes sub-divided into rendering emojis and Draw shapes like circle and line.

In between the goal at the top and the tasks at the bottom lie a number of organisational layers. Each lowest-level task will be one of several that belong to a parent, which represents a logical grouping of tasks. In a program, this corresponds to a collection of related functions that are organised into one place. That place is termed a module .

In Python, a module is a file on the computer’s file system. Each module takes its name from the file it’s contained within (for example the tkinter module has that name because it’s stored in a file called tkinter.py ).

Importing modules

images

Server/client module: when a module uses something provided by another module, the using module can be called the client, whilst the used module can be called the server.

The earlier section on scoping suggested that code in one module couldn’t make use of objects defined in another module. Well, that’s not the whole truth. The client module (see the definition box above) can refer to things in the server module, it just has to import the server module first. We’ve already seen this in earlier examples when importing the tkinter module.

You import modules in several ways. The recommended form to use is the one we’ve already seen (for example, import tkinter ). That’s because different modules may contain objects with the same name, so, to avoid ambiguity, a reference to something in a separate module should be prefixed with that module’s name. That’s why, back at the beginning, we created a canvas by typing c = tkinter.Canvas() instead of just c = Canvas() .

Python also provides the from module import name form, for example:

from tkinter import Canvas.

Referring to a name imported this way doesn’t require you to add a prefix when referencing objects from the server module. Because of this, you should use this form in client modules that are small and use very few other modules (see the box below).

images

The from module import name form may cut down on typing a little, but it can potentially catch you out. Importing just function_a from a module called module_x is done like this: from module_x import function_a , meaning you can refer to function_a without a module prefix. However, if you were subsequently to add your own function_a to your module, then all its existing references to function_a would suddenly point to the one in your module, not the one in module_x .

A variation on the last form is this:

from tkinter import *

This is the ‘wildcard’ form and imports everything from a module automatically. This should generally be avoided because it can pollute your client module with lots of unnecessary names.

Reusable modules

Many modules provide functionality for other modules to use (usually termed library modules ), such as the datetime module mentioned in the previous chapter. In such cases, you should organise your module to promote reusability:

  • Provide functions that are small, focused on one concern, and have a clear purpose.
  • The purpose ought to be recognisable from the function’s signature (see the box definition below), but definitely bolster it with documentation.
  • A function should always behave in the exact same way when given the same input values. To this end:
    • Avoid using global variables in a module. Favour local variables.
    • If a function requires data to work with, provide it via parameters in a function call.
    • If a function’s behaviour can differ between invocations even when given the same input data (for example, it changes depending on the time of day), document this clearly.

images

Function signature: a description of a function made up of its name and an ordered list of the parameters it accepts.

Executable modules

When you import a Python module, the functions it contains are set up ready to execute on request. However, if a module also contains code at the top level (that is, code that is not indented), those instructions are executed immediately.

As opposed to library modules, some modules are intended to be executed as stand-alone programs. These are also called scripts . You should avoid importing executable modules into other modules because the act of importing a module shouldn’t cause visible effects.

Here’s an example script:

images

This program is intended to be run on the command line only. If you import this as a library module into your own program, then your program will start asking the user for their birthdate the instant it runs because the instructions at the top level ( birthdate = get_birthdate() and print_duration(birthdate) ) are executed immediately.

images

A module can be made to function as either a library or a script. To do this, you must make the module find out which context it’s being used in: if it recognises it’s being executed as a script, it should execute the top-level code. If it’s being imported as a library, it shouldn’t execute the top-level code.

To achieve this affect, encapsulate the top-level code like so:

images

The internal variable __name__ is automatically set to ‘__main__’ only when the program is being run from the command line. Thus, the main function will be called only when you use the program as a script.

Example (part 4)

Returning to our example, since the module we’ve written already contains functions for rendering faces, we’ll turn that into the faces module. Definitions for new face images can be added there.

For each new type of image, we’ll add a new module: a vehicles module will draw vehicles, a weather module will draw weather symbols and so on. For example:

images

Our solution now exists as several modules. However, having broken up the solution like this, we’ve exposed ourselves to the same problem we had earlier. At the moment, every module we introduce would have to include the same drawing functions for the rendering functions to use, like these (for example, the weather module uses ovals and lines and so has to include a copy of draw_oval and draw_line ).

It’s the separation of concerns problem all over again. However, it’s not functions that are mixing up rendering and drawing concerns this time, but modules . The rendering modules have to duplicate those exact same drawing functions in every module.

Fortunately, the same solution applies here: split those concerns off and isolate them in one place. Since each module focuses on rendering, we’ll split off the drawing functions and put them in their own library module called core_draw .

images

That will leave us with a collection of rendering modules that each import the core drawing functionality, like this:

images

Modules as interfaces

When you import a module, you may not know how it works internally, especially if you didn’t author that module. And that’s fine. You shouldn’t need to know such details in order to use it. The only thing that should concern you is the interface of the server. The interface is essentially a list of all function signatures in a server module (plus any documentation).

Think of a good interface as an old-fashioned switchboard (see Figure 9.2 ) . From the outside, all you see are a collection of sockets, each with a label telling you where that socket connects to. You have no idea what’s going on behind the switchboard’s front panel, but that doesn’t impede your ability to use it in the slightest.

The benefit of implementing to an interface is that those internals can be changed without affecting a system’s behaviour. Just as an electrician could tinker with the innards of the switchboard, a programmer could alter the internals of a server module and (so long as they made no mistakes) the switchboard operator/client module wouldn’t notice the difference.

Figure 9.2 US Air Force (1967). An old-fashioned switchboard 58

Photograph: A smiling woman working at a telephone switchboard, plugging wires into jacks. Another woman operates a similar station in the background.

More specifically, when programming strictly to an interface:

  • Updating a solution requires fewer changes, thus reducing the risk of introducing new errors.
  • The risk of causing unanticipated knock-on effects is reduced.
  • Modules are more easily reusable.
  • When defined purely in terms of their inputs and outputs:
    • Modules are more easily testable.
    • Modules are swappable, meaning you could replace a server module entirely.
  • It helps you, as the program author, when trying comprehend the behaviour of individual modules and functions.

Information hiding in modules

We’ve already seen how separation of concerns is partly achieved by different parts of a solution knowing little (preferably nothing) about the internals of one another. This principle is called information hiding and this section explores it in more detail.

In one sense, information hiding conceals the structure of information. This means a server module uses it to store its data and ensure that it’s kept secret from the client. As a practical consequence, should that structure change in future, those changes only need to be made in the server module – the client module can remain unchanged.

To illustrate this, let’s say that we replace tkinter with the (fictional) ultra_draw, and that ultra_draw works a little differently. Specifically, some of the function signatures differ. For example, instead of this function:

create_oval(x1, y1, x2, x2, fill)

which tkinter has, ultra_draw has this:

make_oval(x1, x2, y1, y2, fill)

Thankfully, this change will have little impact on the overall solution because we’ve structured it according to good principles of information hiding. We’ve hidden the workings of the drawing functions behind the interface of the core_draw module. Only its unseen internals require updating.

A function in core_draw can change from something this:

images

to this:

images

Because the interface of core_draw remains the same, the clients will still function correctly untouched.

PACKAGES

As a solution grows and its expanding capabilities become more diverse, the need for larger organisational units emerges. Enter packages.

Mechanics of packages

Since expanding to multiple types of images, our example solution has developed a deeper hierarchy. The number of modules has grown and they’ve begun to form logical groupings.

In Python, a group of logically related modules forms a package. For example, drawing and rendering can be considered as two logically distinct concerns. Therefore, the solution could be reorganised to group drawing modules into one package and rendering modules into another.

Like modules, packages take their structure from the way they’re organised on the file system. One possible structure would be as follows:

images

This structure shows a top-level directory called emoji and two subdirectories: drawing and rendering . However, something is missing. At the moment, Python would consider these as directories and nothing more. Each directory and subdirectory needs to contain an extra (empty) file called __init__.py . 57 These files notify Python that the containing directories are in fact Python packages and so can be imported by other code. Hence, the complete file structure would look like this:

images

When importing modules from package hierarchies, you’ll need to use dot notation . We’ve already encountered dot notation, such as when adding something to a list ( list.append() ) or calling a function in another module ( core_draw.draw_line() ). This simply denotes that the thing on the right of the dot belongs to the thing on the left. Similarly, if you write a module that includes this line:

import emoji.drawing.core_draw

this denotes that emoji contains a subpackage called drawing , which contains a module called core_draw . Your module then gets access to all the things defined in the file emoji/rendering/core_ draw.py .

Typical package layout

Python grants the programmer quite some flexibility in the overall structure of their project. Files and folders can be laid out mostly as you wish. One popular layout looks something like this:

images

Applying this to the emoji example would result in this:

images

All materials are stored in the top-level Emoji folder. Its bare-minimum contents would be a subfolder called emoji (note the lower case ‘e’) that contains all executable source code. Additional materials like a documentation folder and a README can also go into the Emoji folder.

SUMMARY

All but the very tiniest programs require careful structuring. Without it, a program becomes an unmaintainable, error-prone mess. This chapter introduced several principles to guide the structuring of programs.

The separation of concerns tells you to divide your program cleanly into pieces, each of which is concerned with one aspect of the program. Reducing the strength of the coupling between those pieces means having them communicate via parameters and using variables with reduced scope.

Modular programming enables you to create large programs made of discrete, reusable components. Python’s module system makes modular programming relatively straightforward. Information hiding encourages you to hide the details of modules behind sensible interfaces.

Finally, Python’s package system allows you to build programs made of multiple modules that form logical groupings.

EXERCISES

EXERCISE 1

Mark the following statements as true or false:

  1. Global variables are the preferred way to pass information between functions.
  2. When functions know too much about other functions’ workings, altering them risks causing side effects.
  3. Objects defined inside a function cannot be referenced outside that function.
  4. A module takes its name from the file it’s defined in.
  5. Files in a Python package may only have names made up of letters or numbers.

EXERCISE 2

What is the output of the following program?

images

EXERCISE 3

Try running this program, and explain why it results in an error:

images

EXERCISE 4

Look back at the example program in section ‘Executable modules’, which calculates how many days the user has been alive. Extend the program so that it also tells the user the following (organise the program so that it could be used as stand-alone or as a library module so each function could be called in isolation):

  1. roughly how many days of their life they’ve spent asleep (assuming 8 hours of sleep per day);
  2. roughly how many times they’ve been to the loo (assuming six visits per day);
  3. roughly how many meals they’ve eaten (assuming three per day).