0

Let's say I want to import some packages or modules but using a string as module names:

import numpy as np

but with numpy as string: 'numpy'

and the same thing with:

from IPython.display import display as dd

I already know:

import numpy as np

is equal to:

np = __import__('numpy')

but when i want to import a module from a package normally imported with the keyword from like:

join = __import__('os.path.join')

I got

ModuleNotFoundError: No module named 'os.path.join'; 'os.path' is not a package

Yet from os.path import join works...

The python documentation (https://docs.python.org/3/reference/simple_stmts.html#from) says:

import foo.bar.baz         # foo.bar.baz imported, foo bound locally
from foo.bar import baz    # foo.bar.baz imported and bound as baz

So, from os.path import join should be equal to import os.path.join, no ?

How to import (for exemple) os.path.join as string, like join = __import__('os.path.join') ?

tharchen
  • 1
  • 1

1 Answers1

2

use importlib instead. Its specifically made for importing module names as strings.

    import importlib
    module = importlib.import_module('numpy')
    print(module.__version__)
    print(module.zeros([3, 3]))