Python non-file packages

The python documentation describing the import system has the following (highlighted by me):

[...] You can consider packages as directories in the file system and modules as files in directories, but do not take this analogy too literally, since packages and modules should not come from the file system . [...]

What options exist for storing modules and packages that do not correspond to files and folders, respectively, in the file system?

I read about the possibility of downloading modules and packages from zip archives. Is this one of the options that this paragraph refers to? Are there any other options?

+4
source share
1 answer

This is how you can think of packages and modules, but it is not necessary that the package / module be a directory / file in the file system.

You can save the package / module in a zip file and download it using zipimport.

You can load the module from a string variable:

import imp

code = """
def test():
    print "function inside module!"
    """

# give module a name
name = "mymodule"
mymodule = imp.new_module(name)
exec code in mymodule.__dict__

>>> mymodule.test()
function inside module!
+1
source

Source: https://habr.com/ru/post/1688349/


All Articles