Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typehints -> None or leave blank

Using python 3, one has the option to use typehints.

My question is, if a function returns None, should one add this, or leave it blank.

i.e.

def hint(p:str) -> None:
    pass

def no_hint(p:str):
    pass

And which PEP addresses this?

like image 494
Daniel Lee Avatar asked Jan 12 '18 09:01

Daniel Lee


People also ask

What are type hints?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.

What is NoReturn in Python?

Special type indicating that a function never returns. For example: from typing import NoReturn def stop() -> NoReturn: raise RuntimeError('no way') New in version 3.5.

What is typing mapping in Python?

typing.Mapping is an object which defines the __getitem__,__len__,__iter__ magic methods. typing. MutableMapping is an object which defines same as Mapping but with __setitem__,__delitem__ magic methods as well. typing.Mapping et al. are based on the abc types in this table.

How do you write a class hint in Python?

In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing. Type ).


1 Answers

Be explicit and always include -> None for functions that return None

That's because otherwise, for functions that don't take arguments, the type checker will assume that you did not use type hints at all. For example, is def foo(): going to return None, or was it simply not type hinted?

PEP 484 - Type Hints indirectly addresses this:

Note that the return type of __init__ ought to be annotated with -> None. The reason for this is subtle. If __init__ assumed a return annotation of -> None, would that mean that an argument-less, un-annotated __init__ method should still be type-checked? Rather than leaving this ambiguous or introducing an exception to the exception, we simply say that __init__ ought to have a return annotation; the default behavior is thus the same as for other methods.

like image 183
Martijn Pieters Avatar answered Oct 12 '22 13:10

Martijn Pieters