Table of Contents
Modules in Python are files that you can import to use in the file you're currently working in. Each module is a different file and you can import as many of them as you want and use the code that is available to you.
Modules are like Amazon packages, but for your code!
Built-in Modules
Python has many built-in modules, and we've already used one extensively in this class, namely the math
module.
Here are some other popular useful built-in modules that might be familiar to you:
- array
- copy
- fileinput
- gc
- gzip
- html
- http
- io
- ipaddress
- json
- keyword
- numbers
- pip
- pipes
- random
- ssl
- statistics
- string
- symbol
- sys
- threading
- time
- token
Creating a Module
To demonstrate modules, let's create a simple one and import it in another file. Again, modules are just normal Python files. Create a file named circles.py
and add this code:
PYTHONimport math
def get_area_of_circle(radius):
return radius * radius * math.pi
Now in an entirely different file, we can do something like this:
PYTHONimport circles
area = circles.get_area_of_circle(5)
print(area)
BASH78.53981633974483
It is truly that simple. When you import a module, you are now free to use the variables and functions inside that file.
Importing Module Objects
You don't necessarily need to import the entire thing. Let's say you only wanted a specific function inside the module. You can import just that function, like so:
PYTHONfrom circles import get_area_of_circle
area = get_area_of_circle(5)
print(area)
BASH78.53981633974483
The output is the same but now if circles.py
had multiple functions inside, you only imported the one you planned to use.
Renaming an Imported Module
One last thing you can do when importing a module is giving it a new name if you want to. Here's how that looks:
PYTHONimport circles as c
area = c.get_area_of_circle(5)
print(area)
BASH78.53981633974483
It's as simple as that! Maybe the original module name is too long, or maybe it conflicts with another module. Renaming is a good way to resolve that issue!
Resources
- How to Install Node on Windows, macOS and Linux
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js