4.3. Storing Functions in Module
One advantage of functions is the way they separate blocks of code from your main program. You can store your function also in a separate file called a module and then importing that module into your main program. An import statement tells Python to make the code in a module available in the currently running program file.
Importing an Entire Module
To start importing functions, we first need to create a module. A module is a file in .py that contains the code you want to import your program. Let's make a module that contains the function make_pizza().
Now, in our main.py, we can import the module in pizza.py and then makes two calls to make_pizza().
To call a function from an imported module, enter the name of the module you imported, pizza, followed by the name of the function, make_pizza(), separated by dot ..
Each function in the module is available through the following syntax:
module_name.function_name()Importing Specific Functions
You can also import a specific function from a module. Here's the general syntax for this approach:
from module_name import function_nameYou can import as many functions as you want from a module by separating each function's name with a comma:
from module_name import func_0, func_1The previous example would look like this if we want to import just the function we're going to use:
Using as to Give a Function an Alias
You can use a short alias (an alternate name, like a nickname) for the function. Here we give the function make_pizza() an alias, mp(), by importing make_pizza as mp. The as keyword renames a function using the alias you provide.
The general syntax for providing an alias is:
from module_name import function_name as fnUsing as to Give a Module an Alias
You can also provide an alias for a module name. Giving a module a short alias, like p for pizza, allows you to call the module's functions more quickly.
The general syntax for this approach is:
import module_name as mnExercise 4.3
Make Sandwich
Make a similar function as make_pizza() called order_stationary(). The first argument is the name of the person who is ordering. The second argument and on are the stationary (pen, pencil, etc.) Put the functions in a separate file called ordering.py. (Click the + button on far right to make a new file) Write an import statement at the top of main.py and modify the file to use the imported functions.Imports
Import the function you made in no. 1 into your main program file using these four approaches. Then, call the function (once each).import module_name
from module_name import function_name
from module_name import function_name as fn
import module_name as mn
from module_name import *