15. Python Modules
Python Modules
Consider a module to be the same as a code library. A module is simply a file containing a set of functions, classes, and variables that you want to include in your application.
As your programs get larger, putting all your code in one massive file becomes impossible to manage. Modules allow you to logically organize your Python code into separate files, making it easier to understand, share, and maintain.
What is a Module?
To create a module, you just save the code you want in a file with the file extension .py. For example, imagine a file named greetings.py containing a single function.
That is it! You have created a module. You can now pull this code into other files without rewriting it.
Using a Module
To use a module in a different file, use the import statement. When you import a module, you access its functions using dot notation.
Variables in Modules
Modules can contain functions, but they can also contain variables of all types (arrays, dictionaries, objects etc). Let's imagine our greetings.py file also contains a dictionary.
We can access this variable from another file just like we accessed the function:
Renaming a Module
If a module name is too long or conflicts with an existing variable, you can create an alias when you import it by using the as keyword.
Import From
You can choose to import only specific parts from a module by using the from keyword. When you do this, you do not use the module name with a dot. You use the function or variable directly.
Built-in Modules
Python comes with a huge "Standard Library" of pre-installed modules that you can import whenever you like. You do not need to install them or create them yourself.
The math Module
One of the most useful built-in modules is math, which provides access to advanced mathematical functions.
The datetime Module
Python does not have a native data type for dates, but we can import a module named datetime to work with dates as date objects.
The dir() Function
If you import a module but aren't sure what functions or variables are inside it, there is a built-in function to list all the names in a module: the dir() function.
Knowledge Check
Ready to test your understanding of 15. Python Modules?