All your __import__ are belong to us
Everyone knows and loves Python's import function. This function is used to import external modules into the current module/script we are writing. Here are a few simple examples illustrating how the function can be used:
Internally, a call to the import function makes a call to the built-in __import__ function. However, there are 2 cases where using import would not work and the only way out is to call __import__ ourselves.
The most common case where we would have to call __import__ directly would be when we want to import specific modules at run-time based on user input. Here is how we might do that:
Yes, I know that we didn't really have to import at run-time in the previous example. It was just meant to be a simple example :)
Another case where we might have to call __import__ is when, for some reason, the parent modules/folders for a module we want to import or a module itself has a name with characters that are not allowed by Python. For example, something like the snippet below would not work:
Notice how the hyphen is not allowed in the module name. Here is how we might work around that: