Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Dynamic Imports With __import__

Give Feedback

The __import__() dunder method is useful when importing modules dynamically. In other words, It can be used to import modules when you aren’t sure what needs to be imported ahead of time. This lesson will show you how to use __import__() , how to use Python strings to initialize imports as well as how dynamic imports affect scope.

00:00 Another thing with that particular import style, what it allows you to do is something like this. Let’s quickly just get out of here real fast. Let’s go back in.

00:08 We’re going to go import sys, and then we’re going to go foo is equal to a string called 'delorean',

00:16 and then we’re going to go delorean is equal to __import__(foo).

00:25 So when we go dir(), we have 'delorean', so we can go delorean.Delorean(),

00:33 and that’ll give us the object that we asked for. Now, the thing that you need to notice there is that… 'foo' you can ignore here because we’re in an interpreter, so anything that gets put here—it’s in our scope, so that makes sense.

00:45 But what the interesting thing here is that we use the string to initialize the import. This is kind of useful for things when you need to dynamically import things, and you’re not particularly sure what needs to be imported.

00:56 So you could have, like, a dictionary of various objects, like so. You could have 'foo' and that is equal to 'delorean', and then you can have some type of lookup when doing imports.

01:08 And that’s the real use of that type of import. There’s another way to do it in importlib, which I think is called import_module(). It provides the same functionality, which I would suggest that you use, but that is another talk altogether.

01:22 Another thing to note, with the from syntax, if you do something like this… We’re going to go back into the Python interpreter. We’re going to go from delorean import Delorean.

01:35 So when you do your dir(), there is no 'delorean' object there, so when you do anything like this, you know that the module is not in scope either, so that’s the whole difference now. So you’d have to do something like this, and then you’d call, and the object is no longer there.

Become a Member to join the conversation.