PEP 302 Example: New Import Hooks

2019-02-12 06:42发布

问题:

Where can I find an example implementation of the "New Import Hooks" described in PEP 302?

I would like to implement a custom finder and loader in the most forward compatible way possible. In other words, the implementation should work in python 2.x and 3.x.

回答1:

You can find thousands of open-source examples e.g. with a google code search, here it is:

http://www.google.com/codesearch?hl=en&lr=&q="imp.find_module"+"imp.load_module"&sbtn=Search

Edit: as the questioner clarified he's looking for example of implementation, not use, a better URL for the search is:

http://www.google.com/codesearch?hl=en&sa=N&q="path_hooks"++lang:python&ct=rr&cs_r=lang:python

One readable example (though NOT suitable for production use, as the reddit discussion points out!) is urlimport.

As for supporting Python 2 and Python 3 at the same time, that sounds ambitious -- I don't know of any existing import hook which claims to. In your shoes, I'd start with offering full support for Python 2.6, then once that's working (and has a good battery of tests and makes nary a peep with the -3 switch), I'd 2to3 the sources and see if anything breaks (if so, find out why, fix the 2.6 sources, iterate).