Home > Articles > Python Functions, Classes, and Modules

Python Functions, Classes, and Modules

Chapter Description

Building Python functions allows for the creation of reusable code and is the first step toward writing object-oriented code. In this sample chapter from Cisco Certified DevNet Associate DEVASC 200-901 Official Cert Guide, you will review working with and building Python functions. It also introduces how Python modules can extend the capabilities of Python and make your job of coding much easier.

Working with Python Modules

key_topic_icon.jpg

A central goal of OOP is to allow you to build modular software that breaks code up into smaller, easier-to-understand pieces. One big file with thousands of lines of code would be extremely difficult to maintain and work with. If you are going to break up your code into functions and classes, you can also separate that code into smaller chunks that hold key structures and classes and allow them to be physically moved into other files, called modules, that can be included in your main Python code with the import statement. Creating modular code provides the following benefits:

  • Easier readability/maintainability: Code written in a modular fashion is inherently easier to read and follow. It’s like chapters in a book providing groupings of similar concepts and topics. Even the best programmers struggle to understand line after line of code, and modularity makes maintaining and modifying code much easier.

  • Low coupling/high cohesion: Modular code should be written in such a way that modules do not have interdependencies. Each module should be self-contained so that changes to one module do not affect other modules or code. In addition, a module should only include functions and capabilities related to what the module is supposed to do. When you spread your code around multiple modules, bouncing back and forth, it is really difficult to follow. This paradigm is called low coupling/high cohesion modular design.

  • Code reusability: Modules allow for easy reusability of your code, which saves you time and makes it possible to share useful code.

  • Collaboration: You often need to work with others as you build functional code for an organization. Being able to split up the work and have different people work on different modules speeds up the code-production process.

There are a few different ways you can use modules in Python. The first and easiest way is to use one of the many modules that are included in the Python standard library or install one of thousands of third-party modules by using pip. Much of the functionality you might need or think of has probably already been written, and using modules that are already available can save you a lot of time. Another way to use modules is to build them in the Python language by simply writing some code in your editor, giving the file a name, and appending a .py extension. Using your own custom modules does add a bit of processing overhead to your application, as Python is an interpreted language and has to convert your text into machine-readable instructions on the fly. Finally, you can program a module in the C language, compile it, and then add its capabilities to your Python program. Compared to writing your own modules in Python, this method results in faster runtime for your code, but it is a lot more work. Many of the third-party modules and those included as part of the standard library in Python are built this way.

Importing a Module

All modules are accessed the same way in Python: by using the import command. Within a program—by convention at the very beginning of the code—you type import followed by the module name you want to use. The following example uses the math module from the standard library:

>>> import math

>>> dir(math)

['__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees',
'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgam-
ma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi',
'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt',
'tan', 'tanh', 'tau', 'trunc']

After you import a module, you can use the dir() function to get a list of all the methods available as part of the module. The ones in the beginning with the __ are internal to Python and are not generally useful in your programs. All the others, however, are functions that are now available for your program to access. As shown in Example 4-4, you can use the help() function to get more details and read the documentation on the math module.

Example 4-4 math Module Help
>>> help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.8/library/math

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.

    acosh(x, /)
        Return the inverse hyperbolic cosine of x.

    asin(x, /)
        Return the arc sine (measured in radians) of x.
-Snip for brevity-

You can also use help() to look at the documentation on a specific function, as in this example:

>>> help(math.sqrt)
Help on built-in function sqrt in module math:

sqrt(x, /)
    Return the square root of x.

If you want to get a square root of a number, you can use the sqrt() method by calling math.sqrt and passing a value to it, as shown here:

>>> math.sqrt(15)
3.872983346207417

You have to type a module’s name each time you want to use one of its capabilities. This isn’t too painful if you’re using a module with a short name, such as math, but if you use a module with a longer name, such as the calendar module, you might wish you could shorten the module name. Python lets you do this by adding as and a short version of the module name to the end of the import command. For example, you can use this command to shorten the name of the calendar module to cal.

>>> import calendar as cal

Now you can use cal as an alias for calendar in your code, as shown in this example:

>>> print(cal.month(2020, 2, 2, 1))


   February 2020
Mo Tu We Th  Fr  Sa Su
                   1  2
 3   4  5  6   7   8  9
10  11 12 13  14  15 16
17  18 19 20  21  22 23
24  25 26 27  28  29

Importing a whole module when you need only a specific method or function adds unneeded overhead. To help with this, Python allows you to import specific methods by using the from syntax. Here is an example of importing the sqrt() and tan() methods:

>>> from math import sqrt,tan
>>> sqrt(15)
3.872983346207417

As you can see here, you can import more than one method by separating the methods you want with commas.

Notice that you no longer have to use math.sqrt and can just call sqrt() as a function, since you imported only the module functions you needed. Less typing is always a nice side benefit.

The Python Standard Library

The Python standard library, which is automatically installed when you load Python, has an extensive range of prebuilt modules you can use in your applications. Many are built in C and can make life easier for programmers looking to solve common problems quickly. Throughout this book, you will see many of these modules used to interact programmatically with Cisco infrastructure. To get a complete list of the modules in the standard library, go to at https://docs.python.org/3/library/. This documentation lists the modules you can use and also describes how to use them.

Importing Your Own Modules

As discussed in this chapter, modules are Python files that save you time and make your code readable. To save the class example from earlier in this chapter as a module, you just need to save all of the code for defining the class and the attributes and functions as a separate file with the .py extension. You can import your own modules by using the same methods shown previously with standard library modules. By default, Python looks for a module in the same directory as the Python program you are importing into. If it doesn’t find the file there, it looks through your operating system’s path statements. To print out the paths your OS will search through, consider this example of importing the sys module and using the sys.path method:

>>> import sys

>>> sys.path

['', '/Users/chrijack/Documents', '/Library/Frameworks/Python.
framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/
Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/
Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/
Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/
site-packages']

Depending on your OS (this output is from a Mac), the previous code might look different from what you see here, but it should still show you what Python sees, so it is useful if you are having trouble importing a module.

If you remove the class from the code shown in Example 4-2 and store it in a separate file named device.py, you can import the classes from your new module and end up with the following program, which is a lot more readable while still operating exactly the same:

from device import Router, Switch

rtr1 = Router('iosV', '15.6.7', '10.10.10.1')
rtr2 = Router('isr4221', '16.9.5', '10.10.10.5')
sw1 = Switch('Cat9300', '16.9.5', '10.10.10.8')

print('Rtr1\n', rtr1.getdesc(), '\n', sep='')
print('Rtr2\n', rtr2.getdesc(), '\n', sep='')

print('Sw1\n', sw1.getdesc(), '\n', sep='')

When you execute this program, you get the output shown in Example 4-5. If you compare these results with the results shown in Example 4-3, you see that they are exactly the same. Therefore, the device module is just Python code that is stored in another file but used in your program.

Example 4-5 Code Results of device.py Import as a Module
Rtr1
Router Model             :iosV
Software Version         :15.6.7
Router Management Address:10.10.10.1

Rtr2
Router Model             :isr4221
Software Version         :16.9.5
Router Management Address:10.10.10.5

Sw1
Switch Model             :Cat9300
Software Version         :16.9.5
Router Management Address:10.10.10.8

Useful Python Modules for Cisco Infrastructure

This chapter cannot cover every single module that you might find valuable when writing Python code to interact with Cisco infrastructure. As you become more familiar with Python, you will come to love and trust a wide range of standard library and third-party modules. The following list includes many that are widely used to automate network infrastructure. Many of these modules are used throughout this book, so you will be able to see them in action. The following list provides a description of each one, how to install it (if it is not part of the standard library), and the syntax to use in your Python import statement:

key_topic_icon.jpg
  • General-purpose standard library modules:

    • pprint: The pretty print module is a more intelligent print function that makes it much easier to display text and data by, for example, aligning data for better readability. Use the following command to import this module:

      from pprint import pprint
    • sys: This module allows you to interact with the Python interpreter and manipulate and view values. Use the following command to import this module:

      import sys
    • os: This module gives you access to the underlying operating system environment and file system. It allows you to open files and interact with OS variables. Use the following command to import this module:

      import os
    • datetime: This module allows you to create, format, and work with calendar dates and time. It also enables timestamps and other useful additions to logging and data. Use the following command to import this module:

      import datetime
    • time: This module allows you to add time-based delays and clock capabilities to your Python apps. Use the following command to import this module:

      import time
  • Modules for working with data:

    • xmltodict: This module translates XML-formatted files into native Python dictionaries (key/value pairs) and back to XML, if needed. Use the following command to install this module:

      pip install xmltodict

      Use the following command to import this module:

      import xmltodict
    • csv: This is a standard library module for understanding CSV files. It is useful for exporting Excel spreadsheets into a format that you can then import into Python as a data source. It can, for example, read in a CSV file and use it as a Python list data type. Use the following command to import this module:

      import csv
    • json: This is a standard library module for reading JSON-formatted data sources and easily converting them to dictionaries. Use the following command to import this module:

      import json
    • PyYAML: This module converts YAML files to Python objects that can be converted to Python dictionaries or lists. Use the following command to install this module:

      pip install PyYAML

      Use the following command to import this module:

      import yaml
    • pyang: This isn’t a typical module you import into a Python program. It’s a utility written in Python that you can use to verify your YANG models, create YANG code, and transform YANG models into other data structures, such as XSD (XML Schema Definition). Use the following command to install this module:

      pip install pyang
  • Tools for API interaction:

    • requests: This is a full library to interact with HTTP services and used extensively to interact with REST APIs. Use the following command to install this module:

      pip install requests

      Use the following command to import this module:

      import requests
    • ncclient: This Python library helps with client-side scripting and application integration for the NETCONF protocol. Use the following command to install this module:

      pip install ncclient

      Use the following command to import this module:

      from ncclient import manager
    • netmiko: This connection-handling library makes it easier to initiate SSH connections to network devices. This module is intended to help bridge the programmability gap between devices with APIs and those without APIs that still rely on command-line interfaces and commands. It relies on the paramiko module and works with multiple vendor platforms. Use the following command to install this module:

      pip install netmiko

      Use the following command to import this module:

      from netmiko import ConnectHandler
    • pysnmp: This is a Python implementation of an SNMP engine for network management. It allows you to interact with older infrastructure components without APIs but that do support SNMP for management. Use the following command to install this module:

      pip install pysnmp

      Use the following command to import this module:

      import pysnmp
  • Automation tools:

    • napalm: napalm (Network Automation and Programmability Abstraction Layer with Multivendor Support) is a Python module that provides functionality that works in a multivendor fashion. Use the following command to install this module:

      pip install napalm

      Use the following command to import this module:

      import napalm
    • nornir: This is an extendable, multithreaded framework with inventory management to work with large numbers of network devices. Use the following command to install this module:

      pip install nornir

      Use the following command to import this module:

      from nornir.core import InitNornir
  • Testing tools:

    • unittest: This standard library testing module is used to test the functionality of Python code. It is often used for automated code testing and as part of test-driven development methodologies. Use the following command to import this module:

      import unittest
    • pyats: This module was a gift from Cisco to the development community. Originally named Genie, it was an internal testing framework used by Cisco developers to validate their code for Cisco products. pyats is an incredible framework for constructing automated testing for infrastructure as code. Use the following command to install this module:

      pip install pyats (just installs the core framework, check
      documentation for more options)

    Many parts of the pyats framework can be imported. Check the documentation on how to use it.

Chapter 5, “Working with Data in Python,” places more focus on techniques and tools used to interact with data in Python. This will round out the key Python knowledge needed to follow along with the examples in the rest of the book.

7. Exam Preparation Tasks | Next Section Previous Section

Cisco Press Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Cisco Press and its family of brands. I can unsubscribe at any time.

Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Cisco Press products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@ciscopress.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children

This site is not directed to children under the age of 13.

Marketing

Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by Cisco Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.ciscopress.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020