6

I have found the following python function definition:

def reverseString(self, s: 'List[str]') -> 'None':

I don't quite understand 'List[str]' and -> 'None'.

I have found that the arrow is a function annotation but I couldn't find anything useful and understandable for List[str].

Is it just an annotation? or does it enforce that the type of parameter s must be a string array?

Amir
  • 317
  • 5
  • 18

3 Answers3

3

It's just python type hinting, You can learn more in PEP 484

Aliakbar Saleh
  • 649
  • 3
  • 10
  • I found the example in [PEP 484 abstract](https://www.python.org/dev/peps/pep-0484/#abstract) to be very useful. Basically, it's function annotation. – Amir Feb 07 '19 at 09:10
2

This is an instance of python3 type hinting. The use of -> 'None' indicates that the function does not have a return statement.

List[str] is more interesting: The List part indicates it will return a list type, and its argument [str] indicates it is a parameterized type. In practice, python lists may contain any type of object, but in strongly-typed language a list is a homogeneous collection.

Using this hint both indicates to a caller of the function that s must contain only strings, thus avoiding any exceptions for whatever operation will be performed, and it also indicates to an intelligent IDE (e.g. PyCharm, VSCode) that the objects contained in the list have string instance methods for autocompletion indicators.

The python interpreter does not do anything with this information in terms type checking, however the mypy interpreter will typecheck your code.

For more information see PEP 484 and the typing module, which has also been backported to pre-3.5 python3 and 2.7.

Bob Zimmermann
  • 938
  • 7
  • 11
  • you can always end a function with `return None`, which I tend to do for clarity. Thus, `-> None` indicates that the function returns `None`, which would occur if there were no return statement, but could also occur with `return None`. Oh and I wouldn't put quote-marks around `None` (as the OP did). – PatrickT Jun 18 '20 at 03:18
1

The list[str] does not really play a role as long as the function is always supplied with an s value when it is called. I tried the function with s: 'something different than list[str]' and it worked the same.


About the arrow issue, just try it:

def reverseString(self, s: 'List[str]') -> 'None':
    pass

Call:

output=reverseString('exampleinput1','exampleinput2')

Then check the output:

print(c)

None

type(output)

NoneType

More info about the arrow here.

zabop
  • 6,750
  • 3
  • 39
  • 84