Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
type annotations
#4
I have looked into it,not used so much in code yet.
I like the concept of gradual typing.
Code without type hints will be ignored by the static type checker.
Therefore can start adding types to where it make sense and critical components,and continue as long as it adds value to you.

A quick look.
from typing import Union

def search_for(needle: str, haystack: str) -> Union[int, None]:
    offset = haystack.find(needle)
    if offset == -1:
        return None
    else:
        return offset

print(search_for('s', "my string"))
So it easy to see that argument to function is strings,and return value from function is integer or None.

mypy on commanline and in VS Code selected as linter.
Wrong input no difference running if with Python(run to TypeError),but mypy will detect it earlier and editors like eg VS Code and PyCharm has detection in editor.
print(search_for(5, "my string"))
[Image: hC9h9G.png]
[Image: QAW83o.png]

Bigger companies like eg Dropbox and Instagram use this heavily think now is almost mandatory for them.
Our journey to type checking 4 million lines of Python
Instagram has made MonkeyType to add type annotations to code where is not automatically.
So can take MonkeyType Shifty for test to see what it dos.
def double(number):
    return number * 2.5

print(double(4))
print(double(5.5))
Output:
10.0 13.75
So can take integer or float as input,and output will be float.
Using MonkeyType:
E:\div_code\read
λ monkeytype apply clean
After apply:
from typing import Union

def double(number: Union[float, int]) -> float:
    return number * 2.5

print(double(4))
print(double(5.5))

Conclusion i quote Python Type Checking (Guide) which is written bye a fellow countryman Geir Arne Hjelle.
It's a well written Guide.
Quote:Conclusion
Type hinting in Python is a very useful feature that you can happily live without.
Type hints don’t make you capable of writing any code you can’t write without using type hints.
Instead, using type hints makes it easier for you to reason about code, find subtle bugs, and maintain a clean architecture.
Reply


Messages In This Thread
type annotations - by perfringo - Sep-26-2019, 09:58 AM
RE: type annotations - by DeaD_EyE - Sep-26-2019, 11:37 AM
RE: type annotations - by micseydel - Sep-26-2019, 09:26 PM
RE: type annotations - by snippsat - Oct-05-2019, 03:44 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020