Home > other >  Is it possible to make value of x equal to id(x)?
Is it possible to make value of x equal to id(x)?

Time:01-29

i just wanted to know if it's possible to make id of a variable, equal to value of it.
i tried brute forcing but there was no luck. what i tried:

x=0
x=id(x)
while x != id(x):
    x = id(x)

another unsuccessful try:

x=0
x=id(x)
while x != id(x):
    x = id(x)   x.bit_length()

when assigning new variable, how does the compiler chose the id for it? what is the pattern?

CodePudding user response:

i found a solution with some unexpected results. this code executes instantly:

from random import randint

x=0
while x!=id(x):
    x=id(x) randint(-1000,1000)

so after running this code, x==id(x) returns True.
but weirdly, x is id(x) and id(x) == id(id(x)) returns False. this was the results i tried:

x == id(x) #True
x == id(id(x)) #False
id(x) == id(id(x)) #False
id(id(x)) == id(id(id(x))) #False
id(id(x)) == id(id(id(id(x)))) #True

i don't understand how x == id(x) but their id is not the same!

CodePudding user response:

I think it is theoretically possible. The id() function in Python returns the memory address of the variable. I think that we can make a specific address (e.g. 0x18dd93a5a50), and fill all the available memory in Python except the specific address. In other words, we make 0x18dd93a5a50 is available and others are all used, and then we assign 0x18dd93a5a50 to x. Actually we should allocate 32 bits to store the integer. However, it is hard to implement because Python cannot assign a value to the specified memory address, we should use C or C to do that (e.g. the code *(long long*) 0x12345678 = 114514 assign 114514 to the address 0x12345678 in the memory (actually the code cannot run because it runs in RING3, but 0x12345678 is in RING0, the OS kernel)).

And answer the question: "when assigning new variable, how does the compiler chose the id for it? what is the pattern?": The compiler (strictly speaking is CPython) doesn't choose the id (memory address) and there is no patterns in it, OS will choose its id.

CodePudding user response:

this code also works, but i don't know if it counts as a valid solution:

def id(x):
    return x
x=0
x==id(x) #True
  •  Tags:  
  • Related