python / python/typing

Option to type default default arguments in Callable types - `WithDefault`

Open
#1,232 5 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

At the moment it's only possible to type callables with default arguments by using a Callback protocol . This adds a lot of additional code for just a few default arguments. Moreover it requires that users have at least a basic understanding of Protocols which is one of the more advanced typing concepts. Lastly, a Callback protocol can't be used to type a generic ParamSpec argument.

Proposal

Add a new WithDefault special type which can be used to annotate arguments in callable types.

Examples
from typing import Callable, TypeAlias, WithDefault

def func(a: str, b: int = 0) -> None: ...
def other(a: str, b: int) -> None: ...

def g(f: Callable[[str, WithDefault[int]], None]) -> None:
    f("Hello")  # ok
    f("World", 2)  # ok

g(func)  # ok
g(other)  # error

For generic ParamSpec types

class Job(Generic[_P]):
    def __init__(self, target: Callable[_P, None]) -> None:
        self.target = target

def g(job: Job[str, WithDefault[int]]) -> None:
    job.target("Hello")  # ok
    job.target("Hello", 2)  # ok

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the proposal's Callable and generic ParamSpec examples, then review how default arguments are currently represented through callback protocols. Define the typing behavior for WithDefault, including acceptance of omitted arguments and rejection of required ones, and validate both examples before considering the feature complete.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.