DEV Community

loading...

Discussion on: How Python Sees Variables

Collapse
alainvanhout profile image
Alain Van Hout

What you describe is also pretty much how Java approaches variables, which is indeed quite different than pointers in C/C++.

Collapse
mcscodes profile image
Mcvean Soans Author

Yes it's a very well said point! But I would like to say that very few languages follow this approach of viewing variables (Python included and not Java). This comes from the fact that Python is dynamically-typed and Java is statically-typed.

When we declare a "variable" in Java, we have to declare the datatype too. This helps JVM to sufficiently allocate memory according to the datatype. In Python, the "object" is given emphasis rather than the "variable". The object is stored in the memory first, and then a "tag" is associated to it.

The main difference between both is that the order in which the memory allocation happens. Java stores the data after the variable has already been created in memory, while Python stores the data (or object) first and then assigns a variable (or tag) to it.

I hope my reasoning has some credibility to it 😄

Collapse
alainvanhout profile image
Alain Van Hout

In general that's true enough, but e.g. when you declare a variable and at that time set it to be equal to an existing variable, then no new memory allocation happens (in Java I mean).

To be honest, I'm not sure whether there would be a memory allocation when you set a variable to null when declaring it.

Thread Thread
mcscodes profile image
Mcvean Soans Author

In Java, null is just a value which a variable can have. It means that the variable refers to nothing, but still space is consumed for the "reference".

Java having two types of memory: stack and heap, primitive types (like int, float), and object references in Java are stored in the stack memory. Objects themselves are stored in the heap memory. Hece, if two int variables contain the same value they will both be stored on the stack.

In Python however there is no separation, and everything is considered to be an object, and every object is stored in the heap memory. If two int variables have the same value, Python optimizes memory on the heap by allowing the variables or "tags" to point to the same object on the heap.

For more info on memory management, you may kindly check out my previous post Python: Memory Management, or a GeeksforGeeks article on Java Memory Management.

Thread Thread
alainvanhout profile image
Alain Van Hout

Yes, primitives are different, but quite a lot in Java is also 'just an object'. That primitives are different is also apparent in the fact that they can't be null.