4 ms·
Perhaps this is a novice question, but what is an instance where one would need to use pointers in python? I am having trouble thinking of an instance where I w
by frankbreetz 7y ago
Perhaps this is a novice question, but what is an instance where one would need to use pointers in python? I am having trouble thinking of an instance where I would need to do this.
- Thorrez 7y agoIf you want to call a C function that takes a pointer as an argument. For example I've called a Windows API function from python which does that.
- ehsankia 7y agoSure, but you only need to because the C function requires you to. I think the person was saying that while coding pure Python, there isn't really anything you would gain by having pointers.
- Thorrez 7y agoYeah, for pure python it's not really needed. Python doesn't need a swap function because it has multiple assignment, python doesn't need output parameters because it has multiple return. Pointers would allow a function to take in a string and replace it with a modified version, but simply returning the modified version would generally be clearer and more flexible. One place where pointers might be useful is if you have some strings spread across a bunch of different objects of different types and you want to do some transformation on all of them. A pointer to each of those strings would mean you could simply modify them instead of having to assign to the containing object. But you can sort of define your own pointer type with a class with one field to solve that problem. The downside of that would be all the objects would have to contain that pointer type instead of the string directly. Another alternative would be getattr/setattr (although that wouldn't work for locals). Or maybe you could rewrite to a visitor pattern. Overall the slight benefit a pointer would provide is outweighed by the complexity it would bring of people wondering how and when to use it.
- ignaloidas 7y agoTechnically python doesn't have multiple return or multiple assignment, it is just automatic tuple packing/unpacking
- pdonis 7y ago> A pointer to each of those strings would mean you could simply modify them You can just use a bytearray if you want a mutable string.
- sametmax 7y agoCalling c/c++ code.
- bigiain 7y agoWhiteboarding a doubly linked list at an interview for a job that mentions Python in the requirements... <smirk>
- Thorrez 7y agoA doubly linked list can be done just fine in python without pointers, because objects use references, and user defined classes are mutable.