Do any type checkers support annotations by decorator?
As you can guess, I don't know how type checkers work -- so my question: given the following annotated function: def foobar(spam, eggs, ham='tasty'): pass If it were annotated via decorator [^1]: @annotate( spam=str, eggs=int, ham=str, ) Would mypy and the others recognize those annotations? -- ~Ethan~ [^1]: the decorator would populate the function's `__annotations__` variable.
El dom, 27 feb 2022 a las 10:46, Ethan Furman (
As you can guess, I don't know how type checkers work -- so my question: given the following annotated function:
def foobar(spam, eggs, ham='tasty'): pass
If it were annotated via decorator [^1]:
@annotate( spam=str, eggs=int, ham=str, )
Would mypy and the others recognize those annotations?
Mypy and most other type checkers will not understand this. A useful way to think about it is that when type checkers see a function call, all they know is the function's signature as it appears in the source code. They do not see what happens inside the function, and there is no way for the function's annotations to express that the function sets its argument's `__annotations__`.
One exception would be the type checker I wrote, pyanalyze. It looks at the runtime function object and would therefore see the annotations that the decorator added at runtime. However, pyanalyze isn't widely used.
-- ~Ethan~
[^1]: the decorator would populate the function's `__annotations__` variable. _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: jelle.zijlstra@gmail.com
On Sun, Feb 27, 2022 at 10:45:04AM -0800, Ethan Furman wrote:
If it were annotated via decorator [^1]:
@annotate( spam=str, eggs=int, ham=str, )
Would mypy and the others recognize those annotations?
Runtime type checkers wouldn't care how the function's `__annotations__` dunder was created, so they wouldn't need to recognise the decorator as special. They would just look at `__annotations__` at runtime. Static type checkers like mypy don't have access to the runtime value of `__annotations__`, so they wouldn't know what the decorator did unless it was a dedicated special tool they were taught to recognise. Do you have a use-case for this? If it is a good use-case, you could have a standard "annotate" decorator added to typing, which type checkers would learn to recognise. Otherwise, no, static checkers like mypy will have no clue what that decorator does. -- Steve
participants (3)
-
Ethan Furman
-
Jelle Zijlstra
-
Steven D'Aprano