feat: improve attribute imports for transparent exceptions
Author: ccrvlhCreated May 8, 2025Updated Aug 16, 2026
Labelsoptimizationfeature
When using strings as function references, app.module.mymodule.MyClass.my_classmethod, when there's an exception when importing mymodule (eg. some library not installed) you still get an attribute error. the rq.utils.import_attribute function could be improved by checking if the import error came from the module itself, or from somewhere else. If the import error came from any other import (eg. library not installed), then the original exception should be raised.
Potential approach:
name_bits = name.split('.')
module_name_bits, attribute_bits = name_bits[:-1], [name_bits[-1]]
module = None
while len(module_name_bits):
try:
module_name = '.'.join(module_name_bits)
module = importlib.import_module(module_name)
break
except ModuleNotFoundError as e:
# Only try fallback if *this* module name wasn't found,
# not if it failed due to a nested import (e.g. tensorflow missing)
if e.name != module_name:
raise # bubble up original error
attribute_bits.insert(0, module_name_bits.pop())
except ImportError as e:
raise eOnly tested this in a couple of specific scenarios, but should help when designing a more robust approach.
Source: rq/rq