Python Modules

In a nutshell, a module is a file with Python code. Instead of having a single Python file that includes all your code, you can use multiple files.

This allows you to organize your code in multiple files, making it easier to reuse and manage your code.










Create and Import Module

To create a new module, we save some Python code in a separate file. We can then import this code from another Python file. Let me show you an example:

In the trinket above, we have two files (see the tab above the code screen). The “main.py” file is our main program and “connect_to_device.py” contains a function that prints a message. We import this file without the .py file extension with the import parameter from the “main.py” file.

Import Module As

Optionally, you can import a module with a different name. Here’s how:

The code above imports the module “connect_to_device” as “ctd”. When you create your own modules, you can decide on the filename. When you import external modules, sometimes it can be useful to rename them to something more meaningful or shorter than the default name.

Variables in Module

Besides functions, we can also import variables from a module. Here is an example:

Import From Module

We don’t have to import the entire module. It’s also possible to import a single function or variable. You use the from parameter to specify the module and the import parameter to specify what you want to import. For example, here’s how to import only the “disconnection_message” function from our “connect_to_device.py” file:

When you import something this way, you don’t have to specify the module name anymore in your code.

Built-In Modules

In the example above, we created our own modules. We don’t have to build everything from scratch though. Python has many built-in modules we can use. With the help function, we can get an overview:

>>> help('modules')
	  

Please wait a moment while I gather a list of all available modules...

__future__          brain_namedtuple_enum hjson               redirector
__main__            brain_nose          hmac                replace
_abc                brain_numpy_core_fromnumeric html                reprlib
_ast                brain_numpy_core_function_base html2text           requestlogger
_asyncio            brain_numpy_core_multiarray http                requests
_bisect             brain_numpy_core_numeric httplib2            requests_oauthlib
_blake2             brain_numpy_core_numerictypes hyperparser         rlcompleter
_bootlocale         brain_numpy_core_umath idle                rpc
_bz2                brain_numpy_ndarray idle_test           rsa
_cffi_backend       brain_numpy_random_mtrand idlelib             rstrip
_codecs             brain_numpy_utils   idna                run
_codecs_cn          brain_pkg_resources imaplib             runpy
_codecs_hk          brain_pytest        imghdr              runscript
_codecs_iso2022     brain_qt            imp                 s3transfer
_codecs_jp          brain_random        importlib           samtranslator
_codecs_kr          brain_re            inspect             sceptre
_codecs_tw          brain_six           io                  sched
_collections        brain_ssl           iomenu              scrolledlist
_collections_abc    brain_subprocess    iosxr_grpc          search
_compat_pickle      brain_threading     ipaddress           searchbase
_compression        brain_typing        isort               searchengine
_contextvars        brain_uuid          itertools           secrets
_csv                browser             jinja2              select
_ctypes             builtins            jmespath            selectors
_ctypes_test        bz2                 jrnl                selectors2
_datetime           cProfile            json                selenium
_decimal            cachetools          jsonpatch           serial
_distutils_findvs   calendar            jsonpointer         setuptools
_dummy_thread       calltip             jsonschema          shelve
_elementtree        calltip_w           jwt                 shlex
_functools          certifi             kappa               shutil
_hashlib            cffi                keyring             signal
_heapq              cfn_clean           keyword             simplejson
_imp                cfn_flip            lambda_packages     site
_io                 cfn_tools           lazy_object_proxy   six
_json               cfnlint             lib2to3             slugify
_locale             cgi                 libfuturize         smtpd
_lsprof             cgitb               libpasteurize       smtplib
[output omitted]

This is a huge list and I didn’t include everything. We can see some interesting modules though. The “JSON” module lets us use JSON in Python. With the “smtplib” module, we can send email through SMTP servers. There’s even the “iosxr_grpc” module which lets us communicate with Cisco IOS-XR routers through GRPC.

In the PIP lesson you learn how to import Python packages you can find on the Internet.

Suppose I want to calculate Pi. I could create my own function, but instead, it’s easier to use the built-in “math” module:

This gets the job done with only two lines of code.

Dir() Function

How do you know what a module offers? We can use the dir function to find out. For example, I can use it to check my “connect_to_device” module:

Or to check the “math” module:

Although this works, I have to say I never use this. If you have Internet access, it’s probably easier just to look up online what the module provides.

Conclusion

You have now learned what Python modules are:

  • A module is a file with Python code that you import into your own code.
  • Modules help to reuse code and build scalable programs.
  • You import a module with the import parameter and the module name (file name without the .py extension).
  • You can import a module with a different name using the as parameter.
  • Instead of importing the entire module, you can also import specific items with the from parameter.
  • Python also has many built-in modules that you can use. You can see them with the help function.
  • The dir function lets you see what a module has to offer.

I hope you enjoyed this lesson. If you have any questions please leave a comment.


Ask a question or start a discussion by visiting our Community Forum