What is the best way to handle ImportError - Raise error or import chain?

Question

When you encounter ImportError in python, should I directly raise the error and ask the user to install it or use the import chain?

Description

I came across this question when I tried to use the lxml package to parse an XML file in python.
The official documentation says:

If your code uses the ElementTree API and does not rely on any functionality specific to lxml.etree, you can also use (any part) the following import chain as a return to the original ElementTree:

try:
    from lxml import etree
    print("running with lxml.etree")
except ImportError:
    try:
        import xml.etree.cElementTree as etree
        print("running with cElementTree on Python 2.5+")
    except ImportError:
        ...

, , :
, lxml, script .

(, lxml ), . , , ImportError.

, , , :

, .

, , , .

, ​​, , ?

+4
2

:

ImportError python, ?

ImportError :

  • , . , .
  • API-, - .
  • , , , , , , , .

:

(, lxml ), .

lxml.etree, ElementTree cElementTree API. . ElementTree -Python , cElementTree . lxml.etree , .

:

try:
    import super_fast_widget as widget
except ImportError:
    try:
        import fast_widget as widget
    except ImportError:
        import slow_widget as widget

, widget , , , - , .

, lxml, . lxml.etree lxml. API .

Django:

# Use the C (faster) implementation if possible
try:
    from yaml import CSafeLoader as SafeLoader
    from yaml import CSafeDumper as SafeDumper
except ImportError:
    from yaml import SafeLoader, SafeDumper

Python . , Python, C.

, , , python:

lxml.etree . (getpass) , ( ). ImportError, .

try if platform.system() == 'Windows' , , , try . getpass - API, , .

+1

, .

Error increase

Traceback (most recent call last):
  File "core.py", line 1, in <module>
ImportError: <error description>

Import Chains

i Importing "lxml.etree"
x Error Importing "lxml.etree"
i Importing "xml.etree.cElementTree" on Python 2.5+
x Error Importing "xml.etree.cElementTree" on Python 2.5+
i Please Install "lxml.etree" or "xml.etree.xElementTree" on Python 2.5+
i Exit with code 1
0
source

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


All Articles