Like Alice in Wonderland, I'll start at the beginning - what's a module anyway? Modules are a way to group related pieces of code together. They allow developers to create a logical container for variables and functions, such that these variables and functions can be used by other programs that require them. The goal? Very simple: by making it possible to share code in this manner, Python immediately makes it easier to create reusable software, cutting down development and testing time. Take it one step further: by allowing developers to create modules and providing the underpinnings to import them into other programs, Python ensures that a single copy of a module is in use across a system. This simplifies code maintenance by restricting updates and upgrades to a single file. In the content of Python programming, a module is essentially a text file, ending in a .py extension and containing executable program code. The name of the file is treated as the name of the module; once the module has been imported into a Python program, this name is used in all subsequent references to the module. Let's illustrate how this works by creating a simple module. Pop open your favourite text editor, and create a new text file containing the following function:
Save this file as "temperature.py" Notice that the module does not require the name of the interpreter to be specified as the first line of the script, as do regular Python scripts. You can now pull this module into any Python program - I'll illustrate how with the command-line interpreter.
blog comments powered by Disqus |