This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: singledispatch does not work with positional arguments with default values.
Type: enhancement Stage:
Components: Versions: Python 3.10, Python 3.9
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: andrei.avk, randolf.scholz
Priority: normal Keywords:

Created on 2022-03-15 18:46 by randolf.scholz, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg415274 - (view) Author: Randolf Scholz (randolf.scholz) Date: 2022-03-15 18:46
from functools import singledispatch
from typing import Optional

@singledispatch
def load(key: Optional[str] = None, /) -> None:
    raise NotImplementedError

@load.register
def _(key: None, /) -> None:
    print(f"loaded {key=}") 

@load.register
def _(key: str, /) -> None:
    print(f"loaded {key=}")
    
load()  # TypeError: load requires at least 1 positional argument
msg415740 - (view) Author: Andrei Kulakov (andrei.avk) * (Python triager) Date: 2022-03-22 03:49
This would be problematic for two reasons:

 - possible confusion between the default function that runs when an argument doesn't match any registered types, and another "default" which runs when argument is omitted.

 - to see which function will run when argument is omitted, you would need to check in two places - the default value of arg and then find the registered function that matches it. If we end up deciding there is a need to run a default handler when an argument is omitted, it would be more explicit and convenient and visually obvious to decorate the "default if no arg" handler in some way, which also means there'd be a single place where this behavior is defined.

We can also consider adding a note to documentation that the first argument used for dispatch should not have a default value, to make it more explicit that dispatching on default value is not supported.
History
Date User Action Args
2022-04-11 14:59:57adminsetgithub: 91186
2022-03-22 03:50:00andrei.avksetnosy: + andrei.avk
messages: + msg415740
2022-03-15 18:46:49randolf.scholzcreate