Python Modules
Learn all about Python Modules in this comprehensive tutorial.
- •Consider a module to be the same as a code library.
- •To create a module just save the code you want in a file with the file extension .
- •Now we can use the module we just created, by using the import statement:
- •The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
- •You can name the module file whatever you like, but it must have the file extension .
- •You can create an alias when you import a module, by using the as keyword:
- •There are several built-in modules in Python, which you can import whenever you like.
- •There is a built-in function to list all the function names (or variable names) in a module.
- •You can choose to import only parts from a module, by using the from keyword.
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Use a Module
Now we can use the module we just created, by using the import statement:
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
Import From Module
You can choose to import only parts from a module, by using the from keyword.
Module quiz
2 questionsWhich of the following is true about Python Modules?
What is the most common pitfall when working with Python Modules?
Answer all questions to submit.