Reputation: 17
I know that the title might not tell exactly what am I asking for, so here's a little block of code that should explain a little bit more:
def echo(msg: any) -> None:
print(str(msg))
Since 'any' is a function, I am asking if syntax like that is correct. I know that I should give a type like 'object' or etc. but I just want to know if the syntax is ok or not.
Upvotes: 0
Views: 460
Reputation: 86
The syntax is really fine. Type annotations just expects you to specify whatever type or object your variable is of. So here in your case its a valid syntax and everything will work fine as any
is object too. Its just a builtin function. If you pass your code through interpreter and inspect the annotations everything will be as expected.
>>> import typing
>>>
>>> def echo(msg: any) -> None:
... print(str(msg))
...
>>>
>>> echo.__annotations__
{'msg': <built-in function any>, 'return': None}
>>>
As you would expect, here msg
is assumed to be of type <built-in function any>
.
However if you pass same using Python type checks like mypy then it would give you an error. So its a valid Python syntax but not valid for Python type checkers as they don't expect builtins as valid types.
And yeah the correct way to do same even if you didn't meant to ask this would be to use typing.Any as like:
import typing
def echo(msg: typing.Any) -> None:
print(str(msg))
Upvotes: 1
Reputation: 110311
any
as the Pythonbuilt-in any is a function. The Any
that should be used in annotations is typing.Any
- which is an annotation marker denoting any possible object.
Usually: the annotation marks should be made with straight out classes, or other specialized objects composed through the typing
library.
Upvotes: 2
Reputation: 7040
I believe you intend for msg
to be any type. The correct code for that would be:
from typing import Any
def echo(msg: Any) -> None:
print(str(msg))
See: https://docs.python.org/3/library/typing.html#typing.Any
In general type annotations should be made with classes and objects from the built-in typing
library, rather than functions like any
.
Upvotes: 1