[Python-ideas] PEP: Distributing a Subset of the Standard Library

Steven D'Aprano steve at pearwood.info
Mon Nov 28 20:14:55 EST 2016


On Tue, Nov 29, 2016 at 09:52:21AM +1100, Chris Angelico wrote:

> +1, because this also provides a coherent way to reword the try/except
> import idiom:
> 
> # Current idiom
> # somefile.py
> try:
>     import foo
> except ImportError:
>     import subst_foo as foo

Nice, clean and self-explanatory: import a module, if it fails, import 
its replacement. Obviously that idiom must die.

*wink*



> # New idiom:
> # foo.missing.py
> import subst_foo as foo
> import sys; sys.modules["foo"] = foo
> #somefile.py
> import foo

Black magic where the replacement happens out of sight.

What if I have two files?

# a.py
try:
    import spam
except ImportError:
    import ham as spam

# b.py
try:
    import spam
except ImportError:
    import cornedbeef as spam


The current idiom makes it the responsibility of the importer to decide 
what happens when the import fails. Perhaps it is as simple as importing 
a substitute module, but it might log a warning, monkey-patch some 
classes, who knows? The important thing is that the importer decides 
whether to fail or try something else.

Your proposal means that the importer no longer has any say in the 
matter. The administrator of the site chooses what .missing files get 
added, they decide whether or not to log a warning, they decide whether 
to substitute ham.py or cornedbeef.py for spam.

I do not like this suggestion, and the mere possibility that it could 
happen makes this entire .missing suggestion a very strong -1 from me.



To solve the simple problem of providing a more useful error message 
when an ImportError occurs, we do not need to execute arbitrary code in 
a .missing.py file. That's using a nuclear-powered bulldozer to crack a 
peanut.



-- 
Steve


More information about the Python-ideas mailing list