Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python 'import' be extended to other archive types than zip?

The zipimport module is automatically used by the standard import to handle .zip sys.path elements.

Is it possible to add hooks to support other file types? for example a handler for .tar.gz?

so for example, if sys.path contains /path/to/archive.tar.gz or /path/to/archive.xyz handlers can be provided to open and read .tar.gz or .xyz files.

like image 923
Dave Lawrence Avatar asked Jun 23 '17 15:06

Dave Lawrence


1 Answers

Yes, there are two ways of doing this:

  1. Overwrite the __builtin__.__import__() function with your own custom implementation. This is a low-level way of completely overriding what the import keyword does, and is not recommended for general use.
  2. Add a finder object to sys.meta_path which implements the desired functionality, or add a callable which returns such a finder to sys.path_hooks. Finders are easier to implement in Python 3 than in Python 2, because 3.x provides a lot of building blocks in importlib. However, they can be implemented in Python 2 as well (you just have to write more code).

In general, (2) is much easier than (1) regardless of 2.x vs 3.x. (1) is only recommended as a last resort. For more on (2), see PEP 302.

like image 184
Kevin Avatar answered Oct 24 '22 04:10

Kevin