Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically importing Python module

I have a trusted remote server that stores many custom Python modules. I can fetch them via HTTP (e.g. using urllib2.urlopen) as text/plain, but I cannot save the fetched module code to the local hard disk. How can I import the code as a fully operable Python module, including its global variables and imports?
I suppose I have to use some combination of exec and imp module's functions, but I've been unable to make it work yet.

like image 976
dpq Avatar asked Sep 26 '10 19:09

dpq


People also ask

How do I import a module dynamically?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);

What is Importlib in Python?

The purpose of the importlib package is two-fold. One is to provide the implementation of the import statement (and thus, by extension, the __import__() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter.

What is lazy import Python?

Lazy import is a very useful feature of the Pyforest library as this feature automatically imports the library for us, if we don't use the library it won't be added. This feature is very useful to those who don't want to write the import statements again and again in their code.


1 Answers

It looks like this should do the trick: importing a dynamically generated module

 >>> import imp >>> foo = imp.new_module("foo") >>> foo_code = """ ... class Foo: ...     pass ... """ >>> exec foo_code in foo.__dict__ >>> foo.Foo.__module__ 'foo' >>> 

Also, as suggested in the ActiveState article, you might want to add your new module to sys.modules:

 >>> import sys >>> sys.modules["foo"] = foo >>> from foo import Foo <class 'Foo' …> >>> 
like image 67
David Wolever Avatar answered Sep 28 '22 15:09

David Wolever