chapter 7 modular designpeople.uncw.edu/vetterr/classes/csc500-fall2019/dierbach...chapter 7 modular...

135
Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions. In complex software systems, however, programs are organized at a higher level as a set of modules, each module containing a set of functions (or objects). Modules, like functions, are a fundamental building block in software development. 1 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons

Upload: others

Post on 06-Jul-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Chapter 7 Modular Design

Until now, we have looked at programs comprised of a set of individual functions. In

complex software systems, however, programs are organized at a higher level as a set of

modules, each module containing a set of functions (or objects). Modules, like functions,

are a fundamental building block in software development.

1Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons

Page 2: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Software systems are some of the most complex entities ever created. Webbrowsers and operating systems, for example, contain as many as 50–100 millionlines of code, and take as long as 10,000 person-years to develop.

We can make complex systems more manageable by designing them as a set ofsubsystems, or modules. For example, NASA’s space shuttle is one of the mostcomplex systems ever engineered, containing more than 2.5 million parts. Themajor components are the orbiter vehicle, a large external liquid-fuel tank, andtwo solid rocket boosters. The orbiter vehicle is composed of several subsystems(e.g., the communications system), which in turn may be composed of sub-subsystems (e.g., the data network system). Although many involved with theshuttle may understand its overall design, only a few individuals need tounderstand or be involved with the detailed design, implementation, and testingof any specific subsystem. The same is true for the modular design of software.In this chapter, we look at the issue of modular program design.

2Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons

Motivation

Page 3: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

3Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons

Modular Design of the NASA Space Shuttle

Page 4: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

We look at the important notion of a “module” in softwaredevelopment.

4Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Modules

Page 5: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

What is a Module?

5Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

The term “module,” broadly speaking, refers to the designand/or implementation of specific functionality to beincorporated into a program.

While an individual function may be considered a module,modules generally consist of a collection of functions (orother entities). The Python turtle module is an example of asoftware module. The use of modules has a number ofadvantages.

Page 6: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

6

Modular design allows large programs to be broken downinto manageable size parts, in which each part (module)provides a clearly specified capability. It aids the softwaredevelopment process by providing an effective way ofseparating programming tasks among various individuals orteams. It allows modules to be individually developed andtested, and eventually integrated as a part of a completesystem.

Finally, modular design facilitates program modificationsince the code responsible for a given aspect of the softwareis localized in a small number of modules, and notdistributed through various parts of the program.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 7: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

7

Benefits of Modular Software Design

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 8: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Module Specification

8

Every module needs to provide a specification of how it isused. This is referred to as the module’s interface.

Any program code making use of a given module is referredto as a client of the module.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 9: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

9

A module’s specification should be sufficiently clear andcomplete so that its clients can effectively utilize it. Forexample, numPrimes is a function that returns the numberof primes in a given integer range.

The function’s specification is provided by the lineimmediately following the function header, called adocstring in Python. A docstring is a string literal denoted bytriple quotes given as the first line of certain programelements.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 10: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

10

The docstring of a particular program element can bedisplayed by use of the __doc__ extension.

This provides a convenient way for discovering how to use aparticular function without having to look at the functiondefinition itself. Some software development tools alsomake use of docstrings.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 11: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

11

How complete is the specification for functionnumPrimes?. At first look it may seem sufficient. However,it does not answer whether the number of primes returnedincludes the endpoints of the range or not.

Also, it is not clear what will happen if the function iscalled with a first argument (start) greater than thesecond (end).

A more complete specification is needed.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 12: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

12

This is a more reasonable specification of the function. Itfollows the Python convention of putting a blank line afterthe first line, which should be an overall description of whatthe function does, followed by an arbitrary number of linesproviding additional details. These additional lines must beindented at the same level, as shown here.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 13: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

13

Here shows the appropriate use of function numPrimes bya client.

Since the user may inappropriately enter a start value greaterthan or equal to the end value, a check is made for a returnedvalue of -1 after the call to numprimes. If -1 is found, thenan error message is output; otherwise, the result is displayed.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 14: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

14

There are potential problems when returning both acomputed result and an error result as a function’s returnvalue.

First, there is no guarantee that the client will perform thenecessary check for the special error value (such as-1 here). Thus, a special error value may be used as a correctresult.

Second, there may not be a special value that can be returnedfor error reporting. For example, if a function is meant toreturn any integer value, including negative numbers, there isno special integer value that can be returned. We will see abetter means of error reporting by a function when wediscuss exception handling in Chapter 8.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 15: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

15Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 16: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

16Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 17: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

17Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 18: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

18Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 19: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

19Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.1 Modules

Page 20: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

One method of deriving a modular design is called top-down design. In this approach, the overall design of asystem is first developed, deferring the specification of moredetailed aspects of the design until later steps. We nextconsider a modular design using a top-down approach forthe calendar year program from Chapter 4.

20

Top Down Design

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 21: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Developing a Modular Design

Let’s consider the development of a modular design for thecalendar year program from Chapter 4 using a top-downdesign approach. The three overall steps of the programare:

• getting the requested year from the user• creating the calendar year structure• displaying the year

21Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 22: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

22

First Stage of Top-Down Design of Calendar Year Program

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 23: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

We consider whether any of these modules needs to befurther broken down. Making such a decision is more of anart than a science.

The goal of modular design is to generate a design in whicheach module provides clearly defined functionality, andcollectively the modules comprise all of the requiredfunctionality of the program. Modules get year and displaycalendar year are not complex enough to require furtherbreakdown. Module construct calendar year, on the otherhand, is where most of the work is to be done.

23Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 24: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

In order to construct a calendar year, it must bedetermined• whether the year is a leap year• what day of the week January 1st of that year falls on• how many days are in each month (accounting for leap years)

Thus, modules leap year, day of week January1, and numdays in month are added as submodules of moduleconstruct calendar year.

The calendar month for each of the twelve months mustthen be constructed, handled by module constructcalendar month.

24Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 25: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

25

Second Stage of Top-Down Design of Calendar Year Program

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 26: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Specification of the Calendar Year Program Modules

The modular design of the calendar year program providesa high-level view of the program. However, there are manyissues yet to resolve in the design. Since each module is tobe implemented as a function, we need to specify thedetails of each function design. For example, it needs to bedecided for each function if it is to be value-returning ornon-value-returning function; what parameters it will take;and what results it will produce. We can give such aspecification by the use of docstrings in Python.

26Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 27: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

27Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 28: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

28Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.2 Top-Down Design

Page 29: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

We next look at the notion of a “module” in the Pythonprogramming language.

29

Python Modules

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 30: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

What is a Python Module?

A Python module is a file containing Python definitions andstatements.

30Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 31: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

When a Python file is directly executed, it is considered themain module of a program. Main modules are given thespecial name __main__.

Main modules provide the basis for a complete Pythonprogram. They may import (include) any number of othermodules (and each of those modules may import othermodules, etc.).

Main modules are not meant to be imported into othermodules.

31Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 32: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

As with the main module, imported modules may contain aset of statements. The statements of imported modules areexecuted only once, the first time that the module isimported. The purpose of these statements is to performany initialization needed for the members of the importedmodule.

The Python Standard Library contains a set of predefinedStandard (built-in) modules. We have, in fact, seen some ofthese modules already, such as the math and randomStandard Library modules.

32Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 33: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Python modules provide all the benefits of modularsoftware design we have discussed.

By convention, modules in Python are named using alllower case letters and optional underscore characters.

We look more closely at Python modules.

33Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 34: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Let’s Try It

34

Create a Python module by entering the following in a file namesimple.py. Then execute the instructions in the Python shell as shownand observe the results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 35: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Modules and Namespaces

A namespace is a container that provides a named contextfor a set of identifiers. Namespaces enable programs toavoid potential name clashes by associating each identifierwith the namespace from which it originates.

In software development, a name clash is when twootherwise distinct entities with the same name become partof the same scope. Name clashes can occur, for example, iftwo or more Python modules contain identifiers with thesame name and are imported into the same program.

35Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 36: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

36

Example of a Name Clash

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 37: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

In Python, each module has its own namespace. Thisincludes the names of all items in the module, includingfunctions and global variables—variables defined within themodule and outside the scope of any of its functions.

The two instances of identifier double, each defined intheir own module, are distinguished by being fully qualifiedwith the name of the module in which each is defined:module1.double and module2.double.

37Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 38: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

38

Example Use of Fully Identified Function Names

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 39: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

The use of namespaces to resolve problems associatedwith duplicate naming is not restricted to computerprogramming. In fact, it occurs in everyday situations.

Imagine, for instance, that you run into a friend who tellsyou that “Paul is getting married.” In fact, you have twofriends in common named Paul.

Because you are not certain which Paul your friend isreferring to, you may respond “Paul from back home, or Paulfrom the dorm?” In this case, you are asking your friend torespond with a fully qualified name to resolve theambiguity: “home:Paul” vs. “dorm:Paul.”

Next, we look at different ways that Python modules can beimported.

39Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 40: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Let’s Try It

40

Enter each of the following functions in their own modules namedmod1.py and mod2.py. Enter and execute the following and observe theresults.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 41: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Importing Modules

The main module of any program is the first (“top-level”)module executed. When working interactively in the Pythonshell, the Python interpreter functions as the main module,containing the global namespace.

The namespace is reset every time the interpreter isrestarted. Module __builtins__ is automaticallyimported in Python programs, providing all the built-inconstants, functions, and classes.

There are various ways of importing modules in Python.

41Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 42: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

When using the import modulename form of import,the namespace of the imported module becomes availableto, but not part of, the importing module.

Identifiers of the imported module, therefore, must be fullyqualified (prefixed with the module’s name) when accessed.Using this form of import prevents any possibility of a nameclash. Thus, as we have seen, if two modules, module1 andmodule2, both have the same identifier, identifier1, thenmodule1.identifier1 denotes the entity of the first moduleand module2.identifier1 denotes the entity of the secondmodule.

42

The “import modulename ” Form of Import

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 43: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Let’s Try It

43

Enter the following into the Python shell and observe the results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 44: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Python also provides an alternate import statement of theform from modulename import something wheresomething can be a list of identifiers, a single renamedidentifier, or an asterisk.

44

The “from-import” Form of Import

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 45: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

45

In (a), only identifiers func1 and func2 are imported

In (b), only identifier func1 is imported, renamed as new_func1in the importing module.

In (c), all of the identifiers are imported, except for those thatbegin with two underscore characters, which are meant to beprivate in the module, which will be discussed later.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 46: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

46

There is a fundamental difference between the

import modulenameand

from modulename import ident1, ident2, …

forms of import in Python.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 47: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

47

When using import modulename, the namespace of theimported module does not become part of the namespace ofthe importing module. Therefore, identifiers of the importedmodule must be fully qualified in the importing module.

modulename.func1

When using from-import, the imported module’s namespacebecomes part of the importing module’s namespace. Thus,imported identifiers are referenced without being fullyqualified,

func1

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 48: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

48

The from modulename import func1 as new_func1form of import is used when identifiers in the imported module’snamespace are known to be identical to identifiers of theimporting module. In such cases, the renamed importedfunction can be used without needing to be fully qualified.

Using the from modulename import * form of import,although convenient, makes name clashes more likely. This isbecause the names of the imported identifiers are not explicitlylisted in the import statement, creating a greater chance that theprogrammer will unintentionally define an identifier with thesame name as in the importing module. And since the from-import form of import allows imported identifiers to beaccessed without being fully qualified, it is unclear in theimporting module where these identifiers come from.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 49: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

49

Module somemodule contains functions func1 and func2. Sincesomemodule is imported using from somemodule import *,identifiers func1 and func2 become part of the main module’s namespace,which already contains identifier func2 (denoting the function defined there).Thus, access to func2 of somemodule is masked, and therefore inaccessible.Using the fully qualified form somemodule.func2 does not work either,since somemodule is not part of the imported namespace for this form ofimport.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 50: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Let’s Try It

50

Enter the following into the Python shell and observe the results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 51: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

In Python, all identifiers in a module are “public”—that is,accessible by any other module that imports it.

Sometimes entities (variables, functions, etc.) in a moduleare meant to be “private”—used within the module, but notmeant to be accessed from outside it.

51

Module Private Variables

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 52: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Python does not provide any means for preventing accessto variables or other entities meant to be private. Instead,there is a convention that names beginning with twounderscores (_) are intended to be private. Such entities,therefore, should not be accessed. It does not mean thatthey cannot be accessed, however.

52Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 53: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

There is one situation in which access to private variables isrestricted.

When the from modulename import * form ofimport is used to import all the identifiers of a module’snamespace, names beginning with double underscores arenot imported. Thus, such entities become inaccessible fromwithin the importing module.

53Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 54: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Module Loading and Execution

Each imported module needs to be located and loaded intomemory. Python searches for modules in the followingorder:

• the current directory• the directories listed in the PYTHONPATH environment var• a Python installation-specific directory (e.g., C:\Python32\Lib)

If still not found, an error (ImportError exception) isreported.

54Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 55: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

For our purposes, all of the modules of a program will bekept in the same directory. However, if you wish to developa module made available to other programs, then themodule can be saved in your own Python modules directoryspecified in the PYTHONPATH environment variable, orstored in the particular Python installation Lib directory.

55Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 56: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

When a module is loaded, a compiled version of themodule with file extension .pyc is automatically produced.The next time that the module is imported, the compiled.pyc file is loaded, rather than the .py file, to save the time ofrecompiling.

A new compiled version of a module is automaticallyproduced whenever the compiled version is out of datewith the source code version of the module when loading,based on the dates that the files were created/modified.

56Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 57: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Built-in function dir() is very useful for monitoring theitems in the namespace of the main module for programsexecuting in the Python shell. For example, the followinggives the namespace of a newly started shell,

57

Built-In Function dir()

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 58: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

The following shows the namespace after importing anddefining variables,

58

Selecting Shell ➝ Restart Shell (Ctrl-F6) in the shell resetsthe namespace,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 59: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Let’s Try It

59

Create the following Python module named simplemodule, import it,and call function displayGreeting as shown from the Python shelland observe the results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 60: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Local, Global, and Built-in Namespaces

During a Python program’s execution, there are as many asthree namespaces that are referenced (“active”)—the built-in namespace, the global namespace, and the localnamespace.

The built-in namespace contains the names of all the built-infunctions, constants, and so on, in Python. The globalnamespace contains the identifiers of the currentlyexecuting module. And the local namespace is thenamespace of the currently executing function (if any).

60Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 61: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

61

Functions sum and max are built-in functions in Python, andthus in the built-in namespace. Built-in function sum returnsthe sum of a sequence (list or tuple) or integers. Built-infunction max returns the largest value of a string, list, tuple, andother types.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 62: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

62

In the module (and thus part of the global namespace) isdefined another function named max. This programmer-defined function returns the index of the largest value from anordered collection of items, not the value itself.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 63: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

63

Which specific functions are called from somefunctiondepends on where the functions are defined. Function sum, forexample, is not defined within the global namespace. Therefore,built-in function sum of the built-in namespace is called.

The call to function max, on the other hand, does not access thebuilt-in function max; rather, it calls function max of the moreclosely defined global namespace. This demonstrates howissues of scope, if not clearly considered, can result in subtleand unexpected program errors. Consider the exampleprogram.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 64: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

64

This program is meant toread in the exam grades ofa class. (The grades arehard-coded here for thesake of example.)

The main module importsmodule grade_calc,which contains functiongrades_highlow, whichreturns as a tuple thehighest grade (with extracredit grades over 100returned as 100) andlowest grade in a list ofgrades.Executing the program, wefind the following results,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 65: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

65

For the list of grades 86, 72, 94, 102, 89, 76, 96, the high and low grades of 72and 100 is correct (counting the grade 102 as 100). The actual highest grade isincorrect, displayed as 100, when it is actually 102. The problem is that thegrade_calc module was imported using

from grade_calc import *

Thus, all of the entities of the module were imported, including the definedmax function. This function returns a “truncated” maximum grade of 100, as asupporting function for function grades_highlow. However, since it isdefined in the global (module) namespace of the classgrades program, thatdefinition of function max masks the built-in max function of the built-innamespace. Thus, when called from within the classgrades program, it alsoproduces a truncated highest grade, returning the actual highest grade of 100instead of 102.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 66: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

66

This example shows care must be taken in the use and naming ofglobal identifiers, especially with use of the from-import *form of import.

Note that if function max were named as a private member ofthe module, __max, then it would not have been imported intothe main module, and the actual highest grade displayed wouldhave been correct.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 67: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Let’s Try It

67

Enter the following in the Python shell: Create a file with the following module:

Create and execute the following program:

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 68: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

A Programmer-Defined Module

In order to demonstrate the development of a programmer-defined module, we present an example stack module.

A stack is a very useful mechanism in computer science.Stacks are used to temporarily store and retrieve data. Theyhave the property that the last item placed on the stack isthe first to be retrieved. This is referred to as LIFO—“last in,first out.”

A stack can be viewed as a list that can be accessed only atone end.

68Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 69: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

69

Three items are pushed on the stack, denoted by A, B, and C. First, item A ispushed, followed by item B, and then item C. After the three items have beenplaced on the stack, the only item that can be accessed or removed is item C,located at the top of stack . When item C is retrieved, it is said to be poppedfrom the stack, leaving item B as the top of stack. Once item B is popped, item Abecomes the top of stack. Finally, when item A is popped, the stack becomesempty. It is an error to attempt to pop an empty stack.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 70: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Following is a Python module containing a set of functionsthat implements this stack behavior. For demonstrationpurposes, the program displays and pushes the values 1through 4 on the stack. It then displays the numbers poppedoff the stack, retrieved in the reverse order that they werepushed.

The stack module consists of five functions—getStack,isEmpty, top, push, and pop. The stack is implemented as alist. Only the last element in the list is accessed—that iswhere all items are “pushed” and “popped” from. Thus, theend of the list logically functions as the “top” of stack.

70Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 71: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

71Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 72: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

72

Here demonstrates the use of the stack module. A new stack is created byassigning variable mystack to the result of the call to function getStack (line 3).Even though a list is returned, it is intended to be more specifically a stack type.Therefore, only the stack-related functions should be used with this variable—the list should not be directly accessed, otherwise the stack may becomecorrupted. Values 1 through 4 are pushed on the stack, and popped in thereverse order,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 73: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

73

Above is the result of pushing values 1 through 4 on the stack, and then popping all the elements from the stack until empty.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 74: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

74

Ensuring that only the provided functions can be used on thestack represents a fundamental advantage of objects. Since anobject consists of data and methods (routines), only themethods of the object can be used to access and alter the data.Thus, the stack type is best implemented as an object, as allother values in Python are. We will see how do to this after theintroduction of object-oriented programming in Chapter 10.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 75: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

We look at a program that determines if a given string is a palindrome. Apalindrome is something that reads the same forwards and backwards. Forexample, the words “level” and “radar” are palindromes. The programimports the stack module developed in the previous section. This programutilizes the following programming feature:

➤ value-returning functions ➤ non-value-returning functions

75

A Palindrome Checker Program

Let’s Apply It

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 76: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

76Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 77: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

77

The stack module is imported online 3 of the program. The importmodulename form of import isused. Therefore, each stackfunction is referenced by stack.function_name.

Lines 6–7 displays the programwelcome. The following linesperform the required initialization.Line 10 sets char_stack to a newempty stack by call to getStack().Line 11 initializes variableempty_string (used fordetermining if the user has finishedentering all the words to check).The string is input by the user online 14. If the string is of length one,then by definition the string is apalindrome. This special case ishandled in lines 17–18 . Otherwise,the complete string is checked.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 78: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

78

First, variable palindrome isinitialized to True. On line 24variable compare_ lengthis set to half the length of the inputstring, using integer division totruncate the length to an equalnumber of characters. Thisrepresents the number ofcharacters from the front of thestring (working forward) that mustmatch the number of characters onthe rear of the string (workingbackwards).

If there are an odd number ofcharacters, then the middlecharacter has no other character tomatch against.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 79: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

79

On lines 27–28 the second half ofthe string chars are pushedcharacter-by-character onto thestack. Then, on lines 31–37 thecharacters are popped from thestack one by one, returning in thereverse order that they werepushed. Thus, the first characterpopped is compared to the firstcharacter of the complete string.This continues until there are nomore characters to be checked. Ifcharacters are found that do nomatch, then is_palindrome is set toFalse ( lines 34–35 ) and the whileloop terminates. Otherwise,is_palindrome remains True. Lines40–43 output whether the inputstring is a palindrome or not, basedon the final value of is_palindrome.Lines 45–46 prompt the user foranother string to enter, and controlreturns to the top of the while loop.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 80: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

80

It is important to mention that the problem of palindromechecking could be done more efficiently without the use of astack. A for loop can be used that compares the characters klocations from each end of the given string. Thus, our use of astack for this problem was for demonstration purposes only. Weleave the checking of palindromes by iteration as a chapterexercise.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 81: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

81Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 82: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

82Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 83: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

83Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 84: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

84Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 85: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

85Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 86: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

86Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 87: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

87Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 88: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

88Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.3 Python Modules

Page 89: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

89

We implement and test a modular design for the calendar yearprogram in the chapter.

Calendar Year Program(modular design)

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 90: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Calendar Year Program

The Problem

90

The problem is that same as stated in the ComputationalProblem Solving section of Chapter 4 – to display a calendaryear for any year between 1800 and 2099, inclusive.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 91: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

91

The problem is to display a calendar year for any year between1800 and 2099, inclusive, as shown below.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 92: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Calendar Year Program

Problem Analysis

92

Since the same problem is being solved as solved before, thealgorithms utilized are also the same—an algorithm forcomputing the day of the week (for the years 1800 to 2099), analgorithm for storing the calendar year, and a means ofdisplaying a calendar year three months across.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 93: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Calendar Year Progeam

Program Design

93

The program requirements, data structures, algorithms, andoverall program steps are the same as specified in Chapter 4.This program will only differ in that we will utilize a modulardesign for the program, as introduced in section 7.2. This willresult in a program that is more easily understood, more easilymodified, and more amenable to program testing.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 94: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

Calendar Year Program

Program Implementation and Testing

94

Now that we are using modular design, we can more easilyincrementally test the program. Given the specification of eachmodule (function), we can first test each function separately tosee if the implementation correctly meets the specification. Theindividual testing of modules is called unit testing.

Once each module is individually tested, they can all be testedtogether. This is called integration testing.

We look at an implementation of the Calendar Year Programbased on the modular design earlier developed.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 95: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

95

Functions getYear, leapYear, anddayOfWeekJan1 (lines 3, 14, and 26)are straightforward, not relying on acall to any other function.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 96: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

96

Function constructCalMonth (lines 65-97) is the largest of all the functions. Ituses the same basic approach as beforeto properly align the weeks for display.In this function, a list of strings iscreated to be output to the screen.

Function numDaysInMonth (lines 49–63) is straightforward, not relying on acall to any other function.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 97: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

97

Function constructCalYear (lines 121-147) relies on calls to functions leapYear,dayOfWeekJan1, numDaysInMonth, andconstructCalMonth.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 98: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

98

Function displayCalendar (lines 149-186) is given a particular calendar yearstructure and displays it in four rows ofmonths, with three months across eachrow.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 99: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

99

The main section of the program, lines 188–207, follows directly from the modulardesign. The first function call is to function getYear (lines 3–12), which ensures that theyear returned is in the range 1800 to 2099.

Next, function constructCalYear (lines 121–147) is called. As seen from the modulardesign, it relies on calls to functions leapYear, dayOfWeekJan1, numDaysInMonth, andconstructCalMonth. The constructed year is a list of lists as given below.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 100: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

To begin, we create a program that contains each of thefunction headers and docstring specifications, andimplement and test them one by one. We first give animplementation for function getYear.

100

Development and Unit Testing of Individual Modules

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 101: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

101

Running this version of the program will not produce anyoutput. However, it will define function getYear, whichtherefore can be unit tested in the Python shell,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 102: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

102Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 103: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

103

Since the getYear function tested OK, we can nextimplement and test function leapYear.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 104: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

104Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 105: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

105

Running this version of the program defines functionleapYear, which can then be unit tested.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 106: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

106

Based on the test results, both functions getYear andleapYear are properly working. Next, we will unit testfunction dayOfWeekJan1.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 107: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

107Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 108: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

108

As with previous stages, running this version of the programdefines function leapYear, which we can then unit test.

Recalling that the values 0–6 represent the days of the weekSaturday to Sunday (where Saturday is 0), checking theseresults with other sources, they are found to be correct.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 109: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

109

Next, we unit test function numDaysInMonth.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 110: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

110

Unit testing function numDaysInMonth, we get thefollowing results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 111: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

111

Obviously, something is wrong with this function!

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 112: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

112

First, we have to make sure that we called it with proper values.The function specification indicates that it should be given valuesin the range 1 to 12, inclusive, as the first argument, and a Booleanvalue (indicating whether the year is a leap year or not) for thesecond. Therefore, it is being called correctly.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 113: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

113

It seems that the results are off by one month. That is,numDaysInMonth(1, False) is 28, correct for February (ofa non-leap year), and numDaysInMonth(2, False) is 31,correct for March.

If the index value used to index list num_days_in_month wereone greater, the results would be consistent with the test results.The fact that an index out of range error occurs for a monthnumber of 12 further supports the likely “off by one” error.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 114: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

114

There is one result that is inconsistent with this hypotheses of an“off-by-one” error.

For February of a leap year, numDaysInMonth(2, True), weget the correct result of 29. This could be explained if the case ofFebruary in a leap year is handled as a special case in the functioncode. In fact, that is exactly the case by the if-else statement.Therefore, we make the needed correction in the function.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 115: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

115

We again test the function, and this time get the correctresult for each test case.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 116: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

116

Since there are only 13 possible sets of input values to thefunction (including two sets for February), we test each oneand find that the function is working for each of the cases.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 117: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

117

Function constructCalMonth is tested next. It ispassed a month number (1 to 12), a day of the week value (0to 6) and the number of days in the month, and returns aconstructed calendar month as follows,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 118: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

118

Additional testing of this function indicates that it is workingcorrectly.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 119: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

The remaining functions to test are constructCalYearand displayCalendar. Function constructCalYearrelies on the use of functions leapYear, dayOfWeekJan1,numDaysInMonth, and constructCalMonth. Since eachof these has been tested and found correct, we can nowperform integration testing of all these functions with functionconstructCalYear.

We execute a version of the program in which all the codedeveloped so far, except these functions, is commented out.

119

Integration Testing of Modules

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 120: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

120

We look at the test results of function ConstructCalYear.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 121: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

121Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 122: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

122

The constructed year looks correct, and so we include thefinal function to be tested, displayCalendar, in thisintegration testing.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 123: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

123

This is not even close to what it should be! The output offunction displayCalendar depends on being given acorrectly structured calendar year. So maybe we should thinkthrough each step of function displayCalendar with the testoutput from function constructCalYear to gain any insightinto the problem.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 124: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

124

The output from function constructCalYear for the year 2012is partially reproduced here.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 125: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

125

Lines 2 and 3 call functions leapYear and dayOfWeekJan1,which have both been tested, so we can assume, for now, that theyare correct. On line 4 , list calendar_year is initialized to a list of oneelement, the integer representing the year. The for loop at line 7 isused to construct each of the calendar months one at a time,appending each to list calendar_year.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 126: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

126

One thing to check is the range of the for loop, since there alwaysmay be an “off by one” error. Here, range is called with a firstargument of 1, and a second argument of 13. Thus, variablemonth_num will be assigned the values 1,2,...,12. The loop williterate, therefore, 12 times—once for each of the 12 months. This isthe correct number of iterations. Now we should check to see if theyare the correct range of values.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 127: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

127

Variable month_num is only used in the call to functionconstructCalMonth on line 11. We check the specificationof the function to see if it requests month values in the range1–12, or if it requests their index values 0–11. Looking back atthe specification for this function, 1–12 is the correct range ofmonth values to be passed to it.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 128: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

128

Next, we consider the concatenation of list calendar_yearwith a newly constructed calendar month each time throughthe loop. This occurs in lines 10–12

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 129: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

129

We know that list calendar_year is initialized to the list[2012]. Also, calls to function constructCalMonth return aconstructed calendar month as a list of the form,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 130: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

130

Thus, the above instructions in lines 10-12 would result in thefollowing,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 131: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

131

Now we realize something! The structure of a calendar year isdesigned to be,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 132: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

132

So we check the initial result of list calendar_year afterdoing a simplified version of the above concatenation in thePython shell,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 133: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

133

Here is a problem! The result of the concatenations should be alist of lists, with each sublist containing a constructed month.The result above is a single list of values. That would certainlybe a cause for function displayCalYear not to workcorrectly. Instead of concatenating the lists, each constructedmonth should be appended to the calendar year list.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 134: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

134

Testing again in the Python shell gives the following (correct)results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program

Page 135: Chapter 7 Modular Designpeople.uncw.edu/vetterr/classes/csc500-fall2019/Dierbach...Chapter 7 Modular Design Until now, we have looked at programs comprised of a set of individual functions

135

This time we get a correctly displayed calendar year.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 7.4 Calendar Year Program