Search code examples
pythonprogramming-languages

why python doesn't need type declaration for python, other way what are the adv. of not declaring type?


If we know the type of variable or parameter very well, why not to declare them?

I'd like to know why it's bad or not necessary.
Sorry, I'm new on Python (from about 1 year) and before I was on C, VB, VB.NET and C# programming languages.

With Python, I hope to have bad parameter types to be catched at compilation time.

And I hope to have an IDE that suggests me every attributes of a variable at design time. May be I'm too Microsoft minded, but variable type declaration seems to be the basic for me.


Solution

  • I'm sure you know the + function. So, what is it's type? Numbers? Well, it works for lists and strings too. It even works for every object that defines __add__. Or in some cases when one object defines __radd__.

    So it's hard to tell the type of this function already. But Python makes it even possible to define these methods at runtime, for example through descriptors or a metaclass. You could even define them based on user input!

    Because Python is so highly dynamic, it's simply impossible for the Python compiler to figure out the type of anything (besides literals) without executing the program. So even if you wrote annotations, you would gain nothing, the type checking would still occur at runtime!