How to Import a Module and Assign an Alias in Python
In this lesson, we're going to walk through how we can alias our import statements in Python.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

I switched back to our main file right here to import helper just by itself, so it's going to bring in the entire helper module. And as you remember whenever we want to call one of the functions inside of helper we need to call the full name of the module so we need to call helper dot and then the function name.

If I switch down here and run this code you can see that this works.

large

Now, I'm going to switch back up to the file and the way that you can use an alias is you can use the exact same syntax, so you say import than the name of the module and then say as and then you can use anything that you want, assuming it's not a reserved word so you can't use something like for or class or def or anything like that. But if you want to say import helper as h then you can come down here and instead of saying helper.greeting you can just say h.greeting and if I saved this file and I come back down here and run it you can see that that still works properly.

large

Now, I can run the exact same process with any of the other code libraries so if I open up the repl I can import the math library as m. And then if I want to say pull in the square root function I can say

m.sqrt(4)

Run it and you can see it works exactly the same way as when we used to have to spell out math entirely.

large

This is going to be a pattern that you'll see in a number of Python programs especially ones that have very large module names so this is a way where you can streamline it and still make it clear on exactly what you are trying to call when you call those functions.

Code

import sys
sys.path.insert(0, './libs')
import helper as h

def render():
    print(h.greeting('Tiffany', 'Hudgens'))


render()


import math as m

m.sqrt(4)