Opened 9 months ago

Last modified 7 months ago

#35090 closed Cleanup/optimization

Enforce uniqueness on custom path converters — at Version 2

Reported by: Adam Johnson Owned by: nobody
Component: Core (URLs) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Adam Johnson)

register_converter() allows custom path converters to silently replace existing converters. This could lead to surprising behaviour, both when two places accidentally use the same custom name or when replacing a default converter. This could be particularly hard to debug if a third-party package uses a custom converter.

For example, say two modules register path converters named “year”. The first allows 1-4 digits:

class YearConverter:
    regex = r"[0-9]{1,4}"
    ...

register_converter(YearConverter, "year")

Whilst the second requires exactly four digits:

class YearConverter:
    regex = r"[0-9]{4}"
    ...

register_converter(YearConverter, "year")

Whichever module is loaded last will silently overwrite the other’s converter. URLs will then only be interpreted with that converter, leading to fewer URLs being matched than intended. This can be particularly difficult to spot as import order may change accidentally due to other code being rearranged.

See the full example project at https://github.com/adamchainz/django-ticket-35090

I propose that support for reusing path converter names be deprecated, eventually raising an exception. I think this should include the default names (int etc.) as replacing them can break URLs from third-party packages.

Change History (2)

comment:1 by Adam Johnson, 9 months ago

Description: modified (diff)

comment:2 by Adam Johnson, 9 months ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top