tlsande
tlsande

Reputation: 109

Python Any from typing vs generic any

I know by PEP 585 on python 3.9 using generic types vs from the typing module is preferred as most types from typing will be deprecated. So does that also hold for the Any type?

I saw from this question: typing.Any in Python 3.9 and PEP 585 - Type Hinting Generics In Standard Collections that using Any from typing should still be fine under PEP 585. Then what is the difference from the Any from typing and the generic any?

It also seems like either way any should be implicit using the generic types for type hints. That I'm not too sure about either.

Here in the python docs it says that "In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any]:" So does that mean using the generic Iterable in a type hint will implicitly mean Iterable[any]/Iterable[Any]?

So along with those questions in mind which of these would be the preferred way to do type hinting?

1:

from typing import Any
from collections.abc import Iterable

def some_function(data: list[Any], events: Iterable[Any]) -> None::
    ...

2:

from collections.abc import Iterable

def some_function(data: list, events: Iterable) -> None::
    ...

3:

from collections.abc import Iterable

def some_function(data: list[any], events: Iterable[any]) -> None:
    ...

Also a sidenote. I'd assume that if you're supporting versions 3.5-3.9 you'd always want to use the typing module for type hinting. I'm mostly looking at this for supporting only versions 3.9 and further.

Upvotes: 9

Views: 8495

Answers (1)

chepner
chepner

Reputation: 531400

any has nothing to do with typing, and is not itself a type. It's a function that returns true when any element of its iterable argument is true.

>>> type(any)
<class 'builtin_function_or_method'>
>>> any([True, True])
True
>>> any([True, False])
True
>>> any([False, False])
False

So no, you cannot replace typing.Any with any. In fact, an attempt to do so will provide a tailor-made error message from mypy:

$ mypy <( echo "x: list[any] = [3]")
/dev/fd/63:1: error: Function "builtins.any" is not valid as a type
/dev/fd/63:1: note: Perhaps you meant "typing.Any" instead of "any"?
Found 1 error in 1 file (checked 1 source file)

(Put another way, typing.Any never had anything to do with any, and the addition of __class_getitem__ that made it possible to use list in place of List isn't applicable here.)


As far as the difference between list and list[Any] (or Iterable and Iterable[Any]), I don't think there is any. Something of type Iterable could produce (an iterator that can produce) values of any type, just like the more explicit Iterable[Any].

Upvotes: 20

Related Questions