
PYTHON — Type Hinting in Python
The best way to predict the future is to invent it. — Alan Kay

PYTHON — Basics of Python Inner Functions
# Understanding Type Hinting in Python
Type hinting in Python is a formal solution to statically indicate the type of a value within your Python code. It was first specified in PEP 484 and introduced in Python 3.5. In this tutorial, we’ll explore how to use type hints to add type information to functions and understand the benefits of type hinting in Python.
Adding Type Information to Functions
You can annotate the arguments and the return value of a function to add type information. Here’s an example of a function with type annotations:
def greet(name: str) -> str:
return "Hello, " + nameIn this example, name: str indicates that the name argument should be of type str, and the -> str syntax indicates that the greet() function will return a string.
Another example is the headline() function, which turns a text string into a headline by adding proper capitalization and a decorative line:
def headline(text: str, align: bool = True) -> str:
if align:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "o")In this example, we’ve added type hints by annotating the arguments and the return value.
Style Recommendations
According to PEP 8, it’s recommended to follow certain style conventions when adding type hints:
- Use normal rules for colons, meaning no space before and one space after a colon (
text: str). - Use spaces around the
=sign when combining an argument annotation with a default value (align: bool = True). - Use spaces around the
->arrow in function definitions (def headline(...) -> str).
Understanding Type Hints in Practice
It’s important to note that type hints have no runtime effect on their own. They are only hints and are not enforced by Python. For instance, using a wrong type for an argument will not produce a runtime error. However, static type checkers such as Mypy can be used to enforce type hints and catch type-related errors at compile time.
When using type hints, static type checkers and integrated development environments (IDEs) can provide visual cues and warnings about mismatched types. This can help in identifying potential type-related issues in your code.
Conclusion
In this tutorial, we’ve explored the basics of type hinting in Python. By using type hints, you can document your code and provide additional information about the types of arguments and return values in your functions. Type hints, combined with static type checkers, can help improve the reliability and maintainability of your Python code.
By following the recommended style conventions and understanding the benefits of type hints, you can take advantage of type hinting to write more robust and predictable Python code.

