Rodrigo πŸπŸš€
Rodrigo πŸπŸš€

@mathsppblog

11 Tweets 8 reads Mar 18, 2023
Python 🐍 is a dynamic language.
But static typing / type hints have been rising in popularity! πŸš€
What are they all about?
I'll explain in this thread. πŸ‘‡
First, what does it mean for Python to be dynamic?
Python is β€œdynamically typed”, which means variables can change types whenever I want.
For example, the variable `x` below:
πŸ‘‰Β starts off an integer;
πŸ‘‰Β it is then converted to a string; and
πŸ‘‰Β it ends a list.
Another staple of dynamic languages is that you don't need to declare a variable before using it.
You can just assign whatever you want to whatever variable you want.
Is this a good thing or a bad thing?
The dynamism of Python gives programmers a lot of power!
But, with great power, comes great responsibility!
And many bugs!
Type hints are an OPTIONAL feature of Python used to declare the types of variables, function parameters, etc.
But what does that look like?
Let us start by looking at the function `multiply` from the beginning of the thread, with and without type hints.
The bottom-right adds type hints:
πŸ‘‰Β `: int` and `: str` to the parameters; and
πŸ‘‰Β `β†’ str` to the return value.
What do they mean?
Type hints are an OPTIONAL indication:
πŸ‘‰Β `factor: int` says β€œI expect this to be an integer”;
πŸ‘‰Β `string: str` says β€œI expect this to be a string”; and
πŸ‘‰Β `β†’ str` says β€œI expect the function to return a string”.
So, what do you think will happen if I run the code below?
Nothing bad will happen!
Notice how the two examples below do not respect the type hints…
But that's fine.
Type hints are optional and just act as guidelines.
You are free to ignore them!
But if they can be ignored, what's the point of them..?
The point is that if you add type hints to your code, it is because you WANT to follow them, not because you NEED to follow them.
When you add type hints and follow them, you may have an easier time using that codebase.
Why?
Type hints act as high-level documentation.
Looking at a variable and knowing its type is better than knowing nothing about it.
Type hints will also warn you when you misuse a variable or a function, which is incredibly useful in complex programs.
These are just 2 advantages.
If you want to learn about type hinting in Python 🐍, you're in for an interesting ride.
You should also DEFINITELY take a look at:
πŸ‘‰Β the module `typing` from the standard library; and
πŸ‘‰Β the tool `mypy`, that will check the types in your code.
Here's a small typed program:
That's it for now!
Typing in Python 🐍 is a huge world in and of itself, so this was just a quick intro.
If this thread was useful, follow me @mathsppblog for more! πŸš€
Comment in the beginning with the topics of typing you would like me to cover. πŸ‘‡

Loading suggestions...