5

I have a method with signature as follows:

def get_users_for_survey(survey_id: (int, str),show_deleted_users: bool = False) -> list:
    pass

I have avoided the method body because I am only interested in the type hinting part for survey_id? Looks like it means it could be either int or str. I thought if that was the intention then it should have been survey_id: Union(int,str). PyCharm is not objecting. Do you think I missed something in PEP 484? I do not think it was meant to be a tuple.

Edit As per answers provided here, this is just a mistake. Now I know what is the origin of this mistake. In the same method next line was:

if survey_id and isinstance(survey_id, (int, str)):

So you see in isinstance if you want to accommodate for multiple types this is a valid syntax. Author of this method thought this is a valid syntax for type hinting as well.Here is a reference: Python isinstance with multiple types

Subhendu Mahanta
  • 753
  • 12
  • 30
  • 3
    Contrary to common expectation, Python's "type hints" are just *annotations*. They can be literally anything. They mean whatever you want them to mean. Meaning: it doesn't have to be "valid" in any way. – deceze Nov 14 '19 at 12:54

3 Answers3

4

Yes, you're right this isn't a valid TypeHint syntax, the valid type hint syntax according to the PEP484 would be

from typing import Union

def get_users_for_survey(survey_id: Union[int, str],show_deleted_users: bool = False) -> list:
    pass

which means the survey_id either be of type int or str.

The second question you asked is "Why PyCharm not complaining about it.?"

Ans:

Rather treating it as an invalid TypeHint, the PyCharm treats it as type None which is equivalent to TypeHint Any means it may be of any type.

Even if you use this syntax for type hint(which is not valid at all)

def get_users_for_survey(survey_id: int or str, show_deleted_users: bool = False) -> list:
    pass

still, there will be no warning or errors.

Akay Nirala
  • 1,086
  • 7
  • 12
0

In short, python type hinting is exactly what it says it is. Type hinting. Python does not check types, however they are good for a couple things:

  1. They help type-checkers
  2. They help with creating documentation

Source: https://stackoverflow.com/a/32558710/9699953 (READ THIS! This is about type-hinting (what it is, how to use it)).

Sxribe
  • 751
  • 5
  • 15
-2

Python "type hints" aren't actually implemented as such, they're just annotations. You can literally annotate your functions and parameters with arbitrary stuff:

>>> def foo(bar: (int, str)): pass
>>> foo.__annotations__
{'bar': (<class 'int'>, <class 'str'>)}

This can mean whatever you want it to mean, and you can use it for arbitrary purposes. Python itself doesn't do anything with it.

I believe the type hint (int, str) is merely meaningless, so type checkers like PyCharm simply don't complain about it.

deceze
  • 471,072
  • 76
  • 664
  • 811