What Does the “-> str” Syntax Signify in Python Functions?

Problem scenario
You see Python code with this "-> str" syntax. What does it do?

Answer
It is purely for readability. To help your coworkers we recommend using the "-> str" syntax if a function returns a string. Otherwise the way to find out is to read the code or temporarily change the code and use type(variable_returned) to show the data type of that which is/was returned.

Here is a program that illustrates how we know the "-> str" is just for information and has no affect on the code:

def documentation_proof() -> str:
  var1 = "unmistakeably a string"
  #have either the above or below var1 definition uncommented. have only one.  it proves the "-> str" syntax is for information only.
  #var1 = 55
  return var1

check_output = documentation_proof()
print(check_output)


Some functions will be configured as "-> None" if the function returns nothing. (If the function actually does return something, the "-> None" will have no effect other than misleading people when they read the function itself.

Similarly, the parameters in a function's definition can display intended data types like this:

def nifty_function(a: int, b: str):

But those parameter data type definitions do nothing special beyond enhancing readability. If you passed a non-integer for "a" or a non-string for "b", the function would proceed as if there was no ": int" or ": str" in the function parameters. Some programmers do not use this explicit convention as it is arguably more prolix and makes the code busy to read.

Leave a comment

Your email address will not be published. Required fields are marked *