Skip to content

Type Hints Examples#30

Open
loganthomas wants to merge 3 commits intodevfrom
type_hints_ex
Open

Type Hints Examples#30
loganthomas wants to merge 3 commits intodevfrom
type_hints_ex

Conversation

@loganthomas
Copy link
Copy Markdown
Collaborator

  • List of type hints examples for reference

  • Notes:

    • Including type hints are a way to "self-document" code.
    • Since Python will always be a dynamically typed language (the authors have no desire to ever make type hints mandatory, even by convention), failure to abide by type hints will never cause a run time error.
    • However, they will help developers when using the code in an IDE if they have a static checker set up.
  • Example consider the add_ints() function below:

def add_ints(x: int, y: int) -> int:
    return x + y
  • Since Python will always remain a dynamically typed language, all the below lines of code will run without error.
print(add_ints(5, 5))
# yields => 10
# This will run without error even though x and y are floats
print(add_ints(5.5, 3.5))
# yields => 9.0
# This will run without error even though x and y are strings
print(add_ints('a', 'b'))
# yields => 'ab'
  • But, with a static type checker installed in my IDE, I will get the below errors:

Screen Shot 2020-09-06 at 17 16 06

Screen Shot 2020-09-06 at 17 16 30

  • The help() builtin function will also show type hints:
help(add_ints)
Help on function add_ints in module type_hints:

add_ints(x: int, y: int) -> int

Copy link
Copy Markdown
Collaborator Author

@loganthomas loganthomas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if you'd like more examples. Happy to add some. Feel free to leave comments inline for things that are confusing. I think you'll like this 😄

Copy link
Copy Markdown
Collaborator Author

@loganthomas loganthomas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if you'd like more examples. Happy to add some. Feel free to leave comments inline for things that are confusing. I think you'll like this 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant