Annotation of `Callable` and `function`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I am experiencing the following problem: I have a function that takes a list of functions with a set default argument. I am annotating this variable with List[Callable] which leads to the following error when I supply a defined list of functions as default argument.
In code, I am e.g. doing this:
from typing import Callable
def fun(x):
return x
def fun2(x, y):
return 2 * x + y
default_functions = [fun, fun2]
def fun3(func: list[Callable] = default_functions):
return func
def fun4(func: list[Callable] = [fun, fun2]):
return func
Expected Behavior
I would have expected that both function definitions are correct: the functions fun1, fun2 are of type Callable and putting them into a list should fulfifl the type annotation.
Actual Behavior
Running mypy on this leads to:
scripts/mypy_callable.py:15: error: Incompatible default for argument "func" (default has type "List[function]", argument has type "List[Callable[..., Any]]") [assignment]
Found 1 error in 1 file (checked 1 source file)
which refers to fun3.
So, there are three things I don't understand here:
- Why is there a difference between fun3 and fun4?
- As far as I understand, function is a subtype of Callable so why wouldn't a default value of type List[function] be acceptable to mypy here?
- If I accept this behavior, how would I annotate the
funcargument withList[function]? Where do I getfunctionfrom? As far as I can see, it is not part of standard Python nor in thetypinglibrary.
Your Environment
(mypy version 0.991, python 3.10.8)
- Mypy version used: 0.991
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.10.8
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the example from the issue, using scripts/mypy_callable.py and the stated mypy command with no flags. Start by tracing how mypy infers the types of default_functions and the inline list, then determine whether the behavior is an error or an intended typing rule; done means the discrepancy is resolved with matching behavior or clearly documented expectations.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100