How to Import a Single Function from a Python Module
So far in this section whenever we've imported a module we've had to explicitly define that module and call it whenever we wanted access to the functions.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So for example here we imported the helper module and then when we wanted access to the greeting function inside of that module we had to call helper.greeting.

large

And if I open up the repl right here if we go back to our math example just to review if I say import math and then I want the square root I have to say math. and then the function name passes that in and that's how I can have access to the functions inside of that module.

However, what happens if you already know the function name that you want access to and you only want to access that one function you don't care about the rest of the library? Well, we can use a slightly different syntax with our import in order to make that work and it makes our code even cleaner and more explicit. So I can say from math import sqrt.

So in review what we have here is instead of just saying import math and that imports the entire math library here. We're saying from the math library I only want you to import the square root function and now if I hit return. Now we have imported only the square root function and what we can do is actually just call square root by itself now, I don't have to say math.sqrt

Now, it works and it has a much cleaner syntax and if I close this down and go back to our example where we have our lib's directory that has our helper module inside of it, I'm going to use the same syntax here. So at the very beginning of this line instead of saying import helper, I'm going to say from helper import greeting.

from helper import greeting

So it's only going to bring in that one greeting function. And now I can get rid of this helper call, save the file. And now if I run python main you can see that we have identical behavior but now our file is much easier to read. We don't have that ugly helper.greeting type of syntax and so whenever you are bringing in some type of module and you know that you only want a single function from it then you can use the syntax and it is a little bit easier to work with.

Code

from math import sqrt

sqrt(4)

import sys
sys.path.insert(0, './libs')
from helper import greeting

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


render()