I
I
Issue2021-08-14 13:47:12
Python
Issue, 2021-08-14 13:47:12

Is it possible to import a library in python3 from a variable?

def include(lib, mod, name):
  from lib import mod as name

lib = 'sys'
mod = 'argv'
name = 'arg'
include(lib, mod, name)

Is it possible to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-08-14
@paulenot

It is possible through importlib

In [1]: import importlib

In [2]: requests.__version__
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-37d800a179a9> in <module>
----> 1 requests.__version__

NameError: name 'requests' is not defined

In [3]: requests = importlib.import_module('requests')

In [4]: requests.__version__
Out[4]: '2.22.0'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question