Skip to content

Creating Code Groupings

Creating Code Groupings

It’s important to group like pieces of code together to make the code easier to use, modify, and understand. As an application grows, managing the code found in a single file becomes harder and harder. At some point, the code becomes impossible to manage because the file has become too large for anyone to work with.

 

The term code is used broadly in this particular case. Code groupings can include:

 

  • Classes
  • Functions
  • Variables
  • Runnable code

 

The collection of classes, functions, variables, and runnable code within a module is known as attributes. A module has attributes that you access by that attribute’s name. Later sections in this chapter discuss precisely how module access works.

 

The runnable code can actually be written in a language other than Python. For example, it’s somewhat common to find modules that are written in C/C++ instead of Python. The reason that some developers use runnable code is to make the Python application faster, less resource intensive, and better able to use a particular platform’s resources. However, using runnable code comes with the downside of making your application less portable (able to run on other platforms) unless you have runnable code modules for each platform

 

 

that you want to support. In addition, dual-language applications can be harder to maintain because you must have developers who can speak each of the computer languages used in the application.

 

The most common way to create a module is to define a separate file contain- ing the code you want to group separately from the rest of the application.

For example, you might want to create a print routine that an application uses in a number of places. The print routine isn’t designed to work on its own but is part of the application as a whole. You want to separate it because the application uses it in numerous places and you could potentially use the same code in another application. The ability to reuse code ranks high on the list of reasons to create modules.

 

To make things easier to understand, the examples in this chapter use  a common module. The module doesn’t do anything too amazing, but it

demonstrates the principles of working with modules. Open a Python File window and create a new file named MyLibrary.py. Type the code found in Listing 10-1 and save it to disk. (This module also appears with the down- loadable  source  code  as  MyLibrary.py.)

 

Listing 10-1:   A Simple Demonstration Module

 

The example code contains two simple functions named SayHello() and SayGoodbye(). In both cases, you supply a Name to print and the func- tion prints it onscreen along with a greeting for you. At that point, the function returns control to the caller. Obviously, you normally create more complicated functions, but these functions work well for the purposes of this  chapter.

 

 

Importing Modules

In order to use a module, you must import it. Python places the module code inline with the rest of your application in memory — as if you had created one huge file. Neither file is changed on disk — they’re still separate, but the way Python views the code is different.

 

 

You have two ways to import modules. Each technique is used in specific circumstances:

 

  • import: You use the import statement when you want to import an entire This is the most common method that developers use to import modules because it saves time and requires only one line of code. However, this approach also uses more memory resources than does the approach of selectively importing the attributes you need, which the next paragraph describes.
  • ..import: You use the from…import statement when you want to selectively  import  individual  module  attributes.  This  method saves resources, but at the cost of complexity. In addition, if you try to use an attribute that you didn’t import, Python registers an error. Yes, the module still contains the attribute, but Python can’t see it because you didn’t import it.

 

Now that you have a better idea of how to import modules, it’s time to look at them in detail. The following sections help you work through importing mod- ules using the two techniques available in Python.

 

 

 

 

 

Using the import statement

The import statement is the most common method for importing a module into Python. This approach is fast and ensures that the entire module is ready for use. The following steps get you started using the import statement.

 

  1. Open the Python Shell.

You see the Python Shell window appear.

  1. Change directories to the downloadable source code

See the instructions found in the “Changing the current Python directory” sidebar.

  1. Type import MyLibrary and press Enter.

Python imports the contents of the MyLibrary.py file that you created  in the “Creating Code Groupings” section of the chapter. The entire library is now ready for use.

It’s important to know that Python also creates a cache of the module in the      pycache  subdirectory. If you look into your source code

directory after you import MyLibrary for the first time, you see the new

  pycache directory. If you want to make changes to your module, you must delete this directory. Otherwise, Python will continue to use the unchanged cache file instead of your updated source code file.

  1. Type dir(MyLibrary) and press Enter.

You see a listing of the module contents, which includes the SayHello() and SayGoodbye() functions, as shown in Figure 10-1. (A discussion of the other entries appears in the “Viewing the Module Content” section of the   chapter.)

 

 

 

 

Figure 10-1:

A direc­ tory listing shows that

Python imports both functions from the module.

 

 

 

  1. Type MyLibrary.SayHello(“Josh”) and press Enter.

The SayHello() function outputs the expected text, as shown in Figure 10-2.

 

 

 

 

 

 

 

Figure 10-2: The Say Hello() function outputs the expected greeting.

 

 

Notice that you must precede the attribute name, which is the Say Hello() function in this case, with the module name, which is MyLibrary. The two elements are separated by a period. Every call to a module that you import follows the same pattern.

  1. Type SayGoodbye(“Sally”) and press Enter.

The SayGoodbye( ) function outputs the expected text.

  1. Close the Python

The Python Shell window closes.

 

 

Using the from…import statement

The from…import statement has the advantage of importing only the attributes you need from a module. This difference means that the module uses less memory and other system resources than using the import state- ment does. In addition, the from…import statement makes the module

a little easier to use because some commands, such as dir(), show less information, or only the information that you actually need. The point is that you get only what you want and not anything else. The following steps dem- onstrate using the from…import statement.

 

 

  1. Open the Python

You see the Python Shell window appear.

  1. Change directories to the downloadable source code

See the instructions found in the “Changing the current Python direc- tory” sidebar.

  1. Type from MyLibrary import SayHello and press Enter.

Python imports the SayHello() function that you create in the “Creating Code Groupings” section, earlier in the chapter. Only this specific function is now ready for use.

You can still import the entire module, should you want to do so. The two techniques for accomplishing the task are to create a list of mod- ules to import (the names can be separated by commas, such as from MyLibrary import SayHello, SayGoodbye) or to use the asterisk (*) in place of a specific attribute name. The asterisk acts as a wildcard character that imports everything.

  1. Type dir(MyLibrary) and press Enter.

Python displays an error message, as shown in Figure 10-3. Python imports only the attributes that you specifically request. This means that the MyLibrary module isn’t in memory — only the attributes that you requested are in memory.

 

 

 

Figure 10-3:

The from… import statement imports only the items that you specifically request.

 

 

  1. Type dir(SayHello) and press Enter.

You see a listing of attributes that are associated with the SayHello() function, as shown in Figure 10-4. It isn’t important to know how these attributes work just now, but you’ll use some of them later in the book.

 

 

 

 

 

 

 

 

 

Figure 10-4:

Use the dir() function to obtain

information about the specific attributes you import.

 

 

  1. Type SayHello(“Angie”) and press Enter.

The SayHello() function outputs the expected text, as shown in Figure 10-5.

 

 

 

 

 

 

 

 

 

 

 

 

Figure 10-5: The Say Hello() function

no longer requires the module

name.

 

 

 

When you import attributes using the from…import statement, you don’t need to precede the attribute name with a module name. This fea- ture makes the attribute easier to access.

Using the from…import statement can also cause problems. If two attributes have the same name, you can import only one of them. The import statement prevents name collisions, which is important when you have a large number of attributes to import. In sum, you must exer- cise care when using the from…import statement.

  1. Type SayGoodbye(“Harold”) and press Enter.

You imported only the SayHello() function, so Python knows noth- ing about SayGoodbye() and displays an error message. The selective nature of the from…import statement can cause problems when you assume that an attribute is present when it really isn’t.

  1. Close the Python

The Python Shell window closes.