__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.
Dynamic Imports With __import__
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.
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.
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.