3 ms·
In Python, objects have types. Variables are best thought of as void* pointers to objects.
by kstrauser 6y ago
In Python, objects have types. Variables are best thought of as void* pointers to objects.
- dr_zoidberg 6y agoI've found over the years that people have an easier time understanding how Python manages variables when you tell them that, rather than "in-memory boxes with data" as is the case in other languages, Python variables are more like "name tags that you attach to an object".
- Spivak 6y agoPointers that also carry the underlying type information.
- kstrauser 6y agoI don’t remember what the CPython implementation looks like, but even if the information is there, it’s not really exposed to end users. “type(foo)” doesn’t return the type of the name “foo”, but of the object that “foo” points to.
- Spivak 6y agoI meant that it's a pointer that is aware of the type of object it's pointing to by virtue of all objects knowing their own type. Same difference I guess. Unlike void pointers or Object references in Java you can't "forget" an object's type.
- kstrauser 6y agoAh, I think I see what you mean. I still think it's more accurate to say that names are just pointers that don't have any typing info themselves (or if they do, it's an implementation detail that doesn't actually get surfaced and isn't a part of the language definition). In Python it doesn't quite make sense to talk about the type of a "name" or "variable" or "pointer" because, because it points to an object, and that's where the canonical type info actually lives.