What gains I have in specifying the type of a function’s argument?
In Python basically is robustness, the compiler could prevent you from calling this function with wrong types (but this is not implemented, so only with external tools is it good for something, which limits its use). Without it, or you test in with code (a possible if
or abstraction from it), or makes too much test of unity, or you trust and pray. There are no performance gains, but it is possible that in the future someone will create certain optimizations, but it is complicated in standard implementation. Python has alternative implementations that already had explicit typing with performance gain, but not there it is not optional.
When I specify the type of argument Python treats it internally without the need to do a validation?
You do it in the parameter and not in argument, and yes, an external tool can validate for you. The argument has always had type, even if implicit.
This also works for classes?
As far as I know, no, because classes do not receive values, only methods from them, but if you want to know if it is accepted in methods (not only parameters), yes, it is accepted. In fact classes and methods now accept to a certain extent Generics (and can use in class inheritance). Yes, Python was totally for static (optional) typing:D As I’ve always said, it’s the future. Of course, not that it requires typing or makes it right, but let you do it with something external if you wish, at least it has a simple and obvious syntax to deal with it, which is a step to have the annotation.
You can read more about PEP from Type Hint. And see Mypy.
And I just found out that the note allows for almost anything, which I’m just not going to call atrocity, because it can give interesting flexibility in the future, but also huge problems.
Duck Typing
Complementing the comments, this has nothing to do with Duck Typing, not even in opposition. The typing of the duck (bad name too) indicates something close to structural typing (It’s not the same thing, it just seems a bit on the static typing side). In fact we are talking about not manifesting typing, nor is it about being dynamic, it is also dynamic, but this is another characteristic. I understand the confusion between these terms, so the link can help. But the term is even disputed by many. Its meaning is not clear and in fact probably speaks of something that already had a more appropriate term, but how funny it is caught.
Related or duplicate: Python 3: Attribute Types
– Woss
(1) Any type other than entirely duck? There are those who consider typing if duck a problem, so to remedy their problems would be to define the type of argument
– Jefferson Quesado
Related: Dynamic typing and team development
– Woss
@Andersoncarloswoss had not understood this question, my eh dup of it, the answer addresses everything.
– gato