Skip to content

python/import-fallback

Pack Severity Fix Versions
Python warning none, edit by hand All versions

A try/except ImportError block that falls back to a second import or sets a module to None keeps a dead compatibility shim alive when you control the runtime environment. Import the single real module directly.

try:
import tomllib
except ImportError:
import tomli as tomllib
import tomllib

The rule reports a try statement whose body imports a module and whose except ImportError or except ModuleNotFoundError handler imports a fallback module or assigns None to a placeholder name.

The rule leaves alone a try/except ImportError guard whose handler raises an error telling the caller which optional extra to install, because that guard fails loudly instead of silently switching implementations.

xpd has no automatic fix, so make the change by hand.

Delete the try/except wrapper and keep the single import that matches your project's declared Python version and dependencies. If a dependency is genuinely optional at runtime, raise a clear ImportError naming the required package instead of binding a silent fallback.

This try/except ImportError block keeps a compatibility import shim alive. Import the single real module directly for the environment you target.

See all rules in the Python pack.