Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use from x import y using importlib in Python

I wanted to install and import a package from script. Then I wanted to add from x import y and from x import * in that script.(I was making some functions actually).

I successfully installed and imported using subprocess and importlib. But I'm at a loss in from x import y and from x import *. Tried these codes and some others.

globals()[package] = importlib.import_module('package','class')
globals()[package] = importlib.import_module('class','package')
globals()[package] = importlib.import_module('package','*')
globals()[package] = importlib.import_module('*','package')
importlib.import_module('gtts','gTTS')
importlib.import_module('gtts','*')

But they didn't work. Shows:

NameError: name 'gTTS' is not defined
ModuleNotFoundError: No module named 'gTTS'

etc.

like image 920
Ratul Hasan Avatar asked Jul 05 '19 12:07

Ratul Hasan


2 Answers

I don't think you can load methods directly, since this method just loads modules. A module is loaded with import module and i defined as "A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. " (check documentation). from x import y does also do the import module but sets another namespace (see discussion here). What you can do is load your module and then set your namespace manually afterwards, this is what the from x import y syntax does. You can load a module with the path (in this example i want to load read_csv from pandas):

importlib.import_module(".io.parsers", "pandas")

(check the path with print(inspect.getmodule(read_csv).__name__))

Also a solution like jottbe mentioned in the commentary would be possible

like image 157
mischva11 Avatar answered Oct 05 '22 07:10

mischva11


The exact syntax to correspond to mischva11's answer, is as follows:

tempmod = importlib.import_module("x_mymodule")
y = x_mymodule.y
del tempmod  # optionally delete the reference to the parent module

Imports only the attribute y from the module x_mymod, similar to from x_mymodule import y. You can get the ... as z functionality by assigning it to any name you want in the 2nd line of code.

I found it useful to delete the parent module from the namespace, when using this in a sub-module, to prevent cluttering up the namespace.

I think to get the import * function you'll have to iterate through the module's attributes and assign them to a named attribute. Here are two hints that help you get there:

  • How to list all functions in a Python module?
  • Set attributes of module from inside the module: https://stackoverflow.com/a/2933481/2453202
like image 27
Demis Avatar answered Oct 05 '22 09:10

Demis