Is it possible to import
a Python module from over the internet using the http
(s
), ftp
, smb
or any other protocol? If so, how? If not, why?
I guess it's about making Python use more the one protocol(reading the filesystem) and enabling it to use others as well. Yes I agree it would be many folds slower, but some optimization and larger future bandwidths would certainly balance it out.
E.g.:
import site
site.addsitedir("https://bitbucket.org/zzzeek/sqlalchemy/src/e8167548429b9d4937caaa09740ffe9bdab1ef61/lib")
import sqlalchemy
import sqlalchemy.engine
In principle, yes, but all of the tools built-in which kinda support this go through the filesystem.
To do this, you're going to have to load the source from wherever, compile it with
compile
, andexec
it with the__dict__
of a new module. See below.I have left the actually grabbing text from the internet, and parsing uris etc as an exercise for the reader (for beginners: I suggest using
requests
)In pep 302 terms, this would be the implementation behind a
loader.load_module
function (the parameters are different). See that document for details on how to integrate this with theimport
statement.At this point
newmodule
is already a module object in scope, so you don't need to import it or anything.Ideone here: http://ideone.com/dXGziO
Tested with python 2, should work with python 3 (textually compatible print used;function-like exec syntax used).
Another version,
I like this answer. when applied it, i simplified it a bit - similar to the look and feel of
javascript
includes over HTTP.This is the result:
Usage:
import_cdn
function in a common library, this way you could re-use this small functionTake a look at: [https://github.com/Asmeble/Languages/raw/Documentation-of-5/13/2018-%22What-you-think-is-left-for-indifference-has-yet-to-shape-or-be-shaped%22/Python3.6/URL_import.py] I use it to import code from my github for development of projects elsewhere.
Although this would be useful for game developers, or web-application designers, and updating your code-base wouldn't take long, even to setup or teardown.
This seems to be a use case for a self-written import hook. Look up in PEP 302 how exactly they work.
Essentially, you'll have to provide a finder object which, in turn, provides a loader object. I don't understand the process at the very first glance (otherwise I'd be more explicit), but the PEP contains all needed details for implementing the stuff.