+ 4
Python â function annotations
Hello. Let's say I have two functions: def func1(num1: int, num2: int) -> int: pass def func2(name: str, age: str) -> str: pass What is the point of parameters annotations? What does it do to the arguments, and what does **-> str** do? Does it specify what type of object to return?
10 Answers
+ 10
Python is dynamically typed, which means that the type of any object is inferred at the moment when the actual line is interpreted.
In statically typed languages, type is verified more rigorously during compilation. This can give the developer some additional assurance, that certain runtime errors would never occur.
With Python this is not the case, you can clearly pass a string argument to a function that expects a number, and the program will happily fail with error when you actually run it.
To make large software systems more reliable, type annotations were introduced to Python. These not only ensure some level of soundness and sanity in the codebase, but also help the developer, or anyone who uses the code, to understand what sort of arguments are required and what type of result is produced.
In your example func2 expects two strings and returns a string.
You can annotate with more complex types, custom objects and containers, by using the typing library.
+ 4
Mirielle you are right, type annotations seems like a waste of time since they don't actually stop you from mixing up your types.
But they are very helpful in development.
IDE's that are properly configured can give you more helpful hints if you use them.
They also make it easier to tell what the code is about.
Think of it like Javascript and Typescript.
It's troublesome, but adds a layer of check WHILE writing the code.
But like everything, good habits are hard to form.
Also, Sololearn app's playground does not use it, so it's pointless here and just clutters your code. But for serious projects, it would be wise to use it.
+ 1
Thanks for explaining
+ 1
But the underlying javascript is not.
also, you missed the keyword "while"
"It's troublesome, but adds a layer of check WHILE writing the code. "
No need to be so flustered, though.
To each his own.
People wouldn't put that much effort into it if it was not useful.
And you would need fundamental changes in Python if you want strong typing. That wouldn't be fun.
Everyone is free to use it or not.
It is not all or nothing.
Sometimes, a little something that could help scratch the itch is useful enough.
0
Mirielle, thanks for explaining
0
But browsers use javascript.
Same for sass and css.