-1

Suppose there is a function written in Python

def functionname() -> int:

Should the programmer must return the int in this function? Or is it acceptable to return nothing but use print()?
Should the programmer must return the same data type as the type hint?

fabioconcina
  • 439
  • 2
  • 7
  • "Should" and "must" typically have different meanings (especially in computing, see e.g. https://tools.ietf.org/html/rfc2119). Why do you think it would be acceptable to not return an int from a function whose return type annotation says it returns an int? – jonrsharpe Apr 13 '21 at 08:14
  • 1
    I thought it is acceptable to not follow type annotation. Isn't type annotation optional? It is allowed to return nothing or print when the annotation is int. – DreamtoSiliconValley Apr 13 '21 at 08:18
  • 2
    If you're not going to follow it, why bother including it at all? It's not enforced by the interpreter, but e.g. MyPy won't like it. – jonrsharpe Apr 13 '21 at 08:21
  • Does this answer your question? [What are type hints in Python 3.5?](https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5) – Gino Mempin Apr 13 '21 at 10:15

1 Answers1

2

It is not necessary to return an int, as in there won't be any error raised if you won't return an int, but if you do not want to return anything or just call a print in the function, it is better to annotate the return type as None and not int.

Edit: If you want it to return None or an int, then you can typehint it as typing.Union[None, int] or typehint.Optional[int]

Vthechamp
  • 636
  • 1
  • 8
  • 20