Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

Notice Board

Per partecipare al corso di Fondamenti di programmazione 2023-24 loggatevi e attivatelo nella vostra pagina dei corsi preferiti. A quel punto il corso appare nel menù personale cliccando sul proprio avatar. Per i materiali degli anni precedenti seguite lo stesso metodo.

To join the Programming/Lab 2023-24 course, log-on and select it on the my courses page. It will appear on the personal menu of your avatar. For earlier years use the same method.

Getting a specific data type as an argument

francesco.calzona (5210 points)
5 20 81
in Programming in Python by (5.2k points)
If you check the latest prof. Spognardi's exercises, you will see that he assigned us some exercises where it is requested to create a function with floats as arguments; apart from rejecting int inputs or using float() to convert ints into floats, is there a way to specify the desired input directly inside the function's argument? And is it better/for what specific purpose you would do it in one way or another?

1 Answer

Ionut Cicio (5960 points)
2 2 43
by (6.0k points)
edited by

In short, yes!

Python does support type annotations https://docs.python.org/3/library/typing.html, but, as stated in the documentation:

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

A few examples

def greeting(name: str) -> str:
    return f'Hello {name}'

def square_root(number: float) -> float:
    return number**.5

Catch fish errors with your friend linter!

Before going on with the boring stuff, let's see how type annotations can be helpful to catch and correct errors. Let's take a simple problem "calculate the square root of user's input".

problem

As you can see from this example, we have an error in our code (a fairly common one in Python)! The main problem is that, to check the error, we have to run and test the code! Let's see what happens with type annotations.


type annotations

Thanks to type annotations, the "linter" (in this case "mypy") is able to tell me that I have two problems in my code, without having to run it! The best part? The errors are way easier to understand!
let's compare the runtime error with linter's error:

Unsupported operand type(s) for ** or pow(): 'str' and 'float'

Argument 1 to "square_root" has incompatible type "str"; expected "float"

Not only the linter is able to catch the mistake, but it can also suggest how to fix it! It also catches another error: in the first case, I would have to correct the first mistake and run the code again to find out that I can't sum a string and a float (which makes sense), but thanks to type annotations, we know that:

Unsupported operand types for + ("str" and "float")

Now, let's take a look to the working code:

working python code

Quick note on linters

Up until now I've talked about linters, but what exactly is a linter? It's a software, a tool, which analyzes a project (or just a file) and tells the developer whether there are any problems! Problems can range from type mismatches (like in the above example) to hints on code style: variables aren't named correctly, or, for example, my linter tells me that a file shouldn't end with a blank line, or that there must be two blank lines between functions definitions. There are a lot of linters for Python, for more info check this article: https://realpython.com/python-code-quality/

w391 blank line at end of file

Blazingly fast

Here's quick and fun a video in which the rich and powerful type system of Rust helps a developer write some code: I have a confession (by ThePrimeagen, one of my favorite tech youtubers)

Ionut Cicio (5960 points)
2 2 43
by (6.0k points)

Work in progress...

Type systems

About dynamic VS static typing

Quick note on type inference

- Python

- Java

- C++

- Rust 

    - simple

    - complex

Weak VS strong typing

Developers heart good type systems

Library example

JavaScript vs Typescript

... is dynamic typing a waste of time?

Move fast break things

P.S.

I had this article twice, in two different answers: the first time, after 4 hours of work I lost everything because when I clicked "save" it didn't actually save the answer, as it had more than 12000 characters, and I reloaded the page. The second time I found out that there's a limit. 

If there are any doubts about my answer, don't hesitate to ask! Even if I made any mistakes that need corrections... I tried to be as concise and clear as possible, and I wrote about a fraction on everything there is to know about type systems and tools.