Ask coding questions

← Back to all posts
Language “sight range”?
Highwayman (1340)

I have no idea how to say this.

In c++, I know everything all the time within reason about my variables.
I know the size of them, I can look at individual bytes or bits, I can find out it’s address, I can find out what type it is even though I already always know what type it is, I can know anything.

And then I go to some language like JavaScript, and all they have is a var.
I have no idea what the var is. I don’t know how big it is, what address it has, what type it is, whether it’s even still a regular variable and not a function... terribly confusing. Almost as bad as template functions in c++.

My point here is actually to ask how deeply I can look into variables and objects in specifically Python. Can you know something’s address? Can you know their type? Can you know their size? And finally how does type casting work in Python. What is happening when I say int(obj)?

Answered by pyelias (1571) [earned 5 cycles]
View Answer
pyelias (1571)

Can you know something's address?

In Python, you will almost never have to deal with memory addresses, but if you need to you can use the ctypes module to get an address (it can also do a few other things that C++ can).

Can you know their type?

Variables are dynamically typed, but you can get the type of an object with the type(obj) function.
For example, type(1) == int.

Can you know their size?

Again, you won't need to, but if you want to know, sys.getsizeof(obj) will find the size of an object (not counting things like elements of an array, see here)

And finally how does type casting work in Python.

Python doesn't have type casting in the same way C++ does. int(obj) just passes obj to int's constructor, which is able to convert types (it can also do user-defined conversions if obj has a __int__ method)

Highwayman (1340)

@pyelias thank you! That was exactly what I was asking for.