Opened 3 weeks ago
Last modified 2 weeks ago
#36956 assigned Cleanup/optimization
import_string logic for AttributeError is too broad, can be improved under Python 3.10+
| Reported by: | Glenn Matthews | Owned by: | Glenn Matthews |
|---|---|---|---|
| Component: | Utilities | Version: | 6.0 |
| Severity: | Normal | Keywords: | import_string |
| Cc: | Triage Stage: | Accepted | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
The logic in import_string that maps AttributeError to ImportError is overly-broad and can be misleading, as any AttributeError raised while importing the requested module will cause Django to report (perhaps misleadingly) that the specific attribute being requested is not defined:
try:
return cached_import(module_path, class_name)
except AttributeError as err:
raise ImportError(
'Module "%s" does not define a "%s" attribute/class'
% (module_path, class_name)
) from err
In Python 3.10 and later, AttributeError has been enhanced (https://docs.python.org/3/library/exceptions.html#AttributeError) to include explicit name and obj parameters, making it easy to tell exactly which specific attribute the error is attributed to.
My proposal is that the above logic should be enhanced to something like the following:
try:
return cached_import(module_path, class_name)
except AttributeError as err:
if err.name and err.name != class_name:
raise
raise ImportError(
'Module "%s" does not define a "%s" attribute/class'
% (module_path, class_name)
) from err
If accepted, I'll be happy to open a PR as described.
Change History (6)
comment:1 by , 3 weeks ago
| Triage Stage: | Unreviewed → Accepted |
|---|
comment:2 by , 3 weeks ago
comment:3 by , 3 weeks ago
| Owner: | set to |
|---|---|
| Status: | new → assigned |
Sriniketh99, Glenn (reporter) already proposed a patch and was interested in preparing a patch.
comment:4 by , 3 weeks ago
I would like to work on this ticket. I plan to implement the proposed logic improvement for Python 3.10+ and add appropriate tests. Please let me know if there are any additional considerations.
comment:6 by , 2 weeks ago
Have a test and fix at https://github.com/django/django/compare/main...glennmatthews:django:ticket_36956. Working on getting the CLA done before opening a pull request.
Hi! I’d like to work on this ticket.
I’m currently learning more about Django internals, and this seems like a good opportunity to understand import_string better. I’ll begin by reviewing the current implementation and reproducing the behavior under Python 3.10+, then work on refining the AttributeError handling as proposed and submit a PR.
Please let me know if there are any additional considerations I should keep in mind.
Thanks!