Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 857
necromancer Avatar asked Sep 23 '10 18:09

necromancer


People also ask

Why we don't need declare variable in Python?

But in Python, we don't declare variables, we simply assign them. In short, we can think of a variable in Python as a name for an object. In the example above, after we reassigned x to a new object, the old object is no longer referenced by any variable and is up for deletion. In other words, it's been overwritten.

Does Python need type declaration?

Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type.

Why Python variables do not have specific type justify?

Mainly because Python is an interpreted language and there isn't really any need of having types. In a compiled language, the data type of each value must be known. Variables go on the stack in a compiled language.

When you program in Python it is not necessary to declare variables types before using them?

Python is one of the Dynamically Typed Languages, which mean doesn't need to declare variable before use it. The data types are usually same with other programming languages. Besides its advantages, there is some vulnerabilities that can cause issue in the future.


1 Answers

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!

like image 52
Jochen Ritzel Avatar answered Oct 12 '22 23:10

Jochen Ritzel