If you are cOFrom C or Java, setting the data types does not seem new. But if you’re learning Python, almost zero online courses and books mention data type definitions to keep things simple.

As the code base grows, type tips can help with debugging and prevent stupid errors. If you are using an IDE, such as PyCharm, you will receive a warning message whenever you use the wrong data type, provided you use type hints.

Let’s start by simply examining the function without type hints:

def add_numbers(num1, num2):
return num1 + num2
print(add_numbers(3, 5)) # 8

There is nothing groundbreaking here, but I have reported such a function on purpose, because adding numbers should work as both integers and floating. We’ll discuss how to determine both with type tips later.

Here’s how to add type tips to our function:

  • Add a colon and data type after each function parameter
  • Add arrow (->) and after the function of determining the type of recovery data, the data type

Per code, you should make these changes:

def add_numbers(num1: int, num2: int) -> int:
return num1 + num2
print(add_numbers(3, 5)) # 8

Neat. If you are working with a function that should not return anything, you can specify None return type:

def add_numbers(num1: int, num2: int) -> None:
print(num1 + num2)
add_numbers(3, 5) # 8

Finally, you can also set a default value for the parameter as shown below:

def add_numbers(num1: int, num2: int = 10) -> int:
return num1 + num2
print(add_numbers(3)) # 13

Everything is great, but what if we decide to call add_numbers() function with floating point numbers? Checking:

def add_numbers(num1: int, num2: int) -> int:
return num1 + num2
print(add_numbers(3.5, 5.11)) # 8.61

As you can see, everything still works. Adding type hints has no runtime effects by default. Static type checker mypy can solve this “problem”, but more on that later.

Next, the notations of the variables are examined.

LEAVE A REPLY

Please enter your comment!
Please enter your name here