M
M
mkone1122021-01-01 09:31:28
Python
mkone112, 2021-01-01 09:31:28

How to use pointers in python?

How to implement this behavior in python?

#include <iostream>

using namespace std;

void change(char* a, char* b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}

int main(void)
{
    char a = 'x';
    char b = 'y';
    printf("a=%c, b=%c\n", a, b);
    change(&a, &b);

    printf("a=%c, b=%c\n", a, b); 
}

I'm not interested in something banal, like increasing an int by one, but let's say a complete replacement of one instance of an object with another. Any methods will do, maybe this can be implemented by replacing a piece of code in cpython? Or can it be done with cython? Maybe some python implementations like pypy can do this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mkone112, 2022-01-04
@mkone112

Hell yes! It's possible. Of course, at the moment there is a variant with a bunch of crutches, but they can be greatly improved.

>> s = 'string'
>> w = Proxy(s)
>> isinstance(w, str), id(w)
True, 1680141601288
>> print(w)
string
>> w.__wrapped__ = [1, 2, 3]
>> isinstance(w, list), id(w)
True, 1680141601288
>> print(w)
[1, 2, 3]

PS repelled from https://wrapt.readthedocs.io/en/latest/wrappers.html

D
Dr. Bacon, 2021-01-01
@bacon

Well, the banal one x, y = y, xwill do the same, no? (Now I'm trying to remember how it was in dereferences ;)). and pypy is the same python, but with JIT compilation

S
Sergey Pankov, 2021-01-02
@trapwalker

Here, it seems, there is a misunderstanding of how variables are arranged in python and how they differ from variables (and partly pointers) in C.
In C (and not only, in Pascal, for example, too) a variable is a box that already exists and you can put something into it by replacing some garbage that was there before, then its contents can be replaced.
In Python, a variable is like a label. The label is the name, and everything around is the objects. You can hang many tags on one object (think of a tea bag tag). Each label is a separate name or position in a list, tuple, dictionary...) There is only one object, but there can be many references to it. The label can be destroyed or moved to another object. When there is not a single label attached to an object, it becomes a candidate for deletion and release of memory.
You were shown in an adjacent answer how you can elegantly exchange names of two objects in python. Yes, exactly, the names will change places, but the objects will remain as they were. It's like changing the plates on the offices of the director and chief accountant.
So, in a way, all variables in python are smart weak references.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question