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
  • email
  • 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:

PYTHON
import math def get_area_of_circle(radius): return radius * radius * math.pi

Now in an entirely different file, we can do something like this:

PYTHON
import circles area = circles.get_area_of_circle(5) print(area)
BASH
78.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:

PYTHON
from circles import get_area_of_circle area = get_area_of_circle(5) print(area)
BASH
78.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:

PYTHON
import circles as c area = c.get_area_of_circle(5) print(area)
BASH
78.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

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.