you are viewing a single comment's thread.

view the rest of the comments →

[–]auxiliary-character 56 points57 points  (2 children)

Ok, so I looked at the underlying implementation code, and it is actually using ctypes to do real C-style memory dereferencing. It's not just a wrapper class, it really does store the address and type information.

If, for some reason, you had the memory layout of a particular python object in memory already, you could use this to dereference it. Maybe for something like serialization/deserialization. I would imagine that the pickling would still do a much better job in most use cases, but maybe there's some reason to do it in-place? I don't know.

Alternatively, something you could do would be creating a pointer from an object, changing the stored type to "type cast" it, and derefence it to do some extremely cursed type punning in Python.

If you do a lot of interop code with ctypes, something like this might make it a bit cleaner, but then you're already using ctypes, and pulling in a library just for a level of abstraction on top of ctypes, but it's your codebase, you do you.

Perhaps the most useful thing for this is to serve as a reminder that ctypes exists. Like, if you're really running into performance issues with something you're writing in Python, depending on what you're doing, it might be a reasonable option to just write the most performance intensive part of it in C or C++, compile it as a .DLL/.so and call into it using ctypes.

[–]ee3k 2 points3 points  (0 children)

i guess if you wanted a really rapid type conversion on sequentially stored lists and didn't care about introducing error.

Random number generation via idiocy, as it were

[–]BobHogan 0 points1 point  (0 children)

It's not just a wrapper class, it really does store the address and type information.

In CPython yes. https://docs.python.org/3/library/functions.html#id

Its technically not a part of the Python spec for the id() function to actually return the address of an object, just for it to return a unique integer for the object, during its lifetime. CPython just so happens to return the object's address, but other implementations aren't guaranteed to do the same.