Understanding memory location of Python variables

Chris Angelico rosuav at gmail.com
Sun Jun 17 06:26:48 EDT 2018


On Sun, Jun 17, 2018 at 8:01 PM, Bart <bc at freeuk.com> wrote:
> On 17/06/2018 03:28, Grant Edwards wrote:
>>
>> On 2018-06-16, ip.bcrs at gmail.com <ip.bcrs at gmail.com> wrote:
>>
>>> I'm intrigued by the output of the following code, which was totally
>>> contrary to my expectations. Can someone tell me what is happening?
>>>
>>>>>> myName = "Kevin"
>>>>>> id(myName)
>>>
>>> 47406848
>>>>>>
>>>>>> id(myName[0])
>>>
>>> 36308576
>>>>>>
>>>>>> id(myName[1])
>>>
>>> 2476000
>>
>>
>> What's happening is that you're paying attention to the values
>> returned by id(), when you should not.  The fact that CPython returns
>> a VM address when you call id() is just an "accident" of that
>> particular implimentation.  You shouldn't assume that id() returns
>> anything other than a number that is unique to each object.  Any time
>> you spend worrying about how that number is calculated is proably
>> wasted.
>>
>>> I expected myName[0] to be located at the same memory location as the
>>> myName variable itself.
>>
>>
>> Python is not C.
>>
>>> I also expected myName[1] to be located immediately after myName[0].
>>
>>
>> Python is not C.
>>
>> Just in case you missed that...
>>
>> Python is not C.
>>
>
> So, how /do/ you obtain the memory address of those values are located? For
> example, in order to pass it to some foreign C function that takes a void*
> parameter.

For strings? You don't.

> I assume there is a memory address at least for the "Kevin" value, as the
> other two might yield temporary objects for "K" and "e" rather the in-place
> strings which are the first and second characters of the name.
>

You assume wrong.

Now, if you're talking about a data type that DOES have a concrete
in-memory representation (such as memoryview), then the answer may be
different. But in Python, no, you cannot find out where the data is
located, because it quite probably isn't stored in any way that would
be useful to you.

If you're implementing a function *in C* that needs to accept a Python
string as a parameter, you can take that string object and say "hey
Python, can you give me a UTF-8 buffer with the contents of this
string pls thx?", and you'll get one. But that's a conversion - albeit
one that may be cached.

ChrisA



More information about the Python-list mailing list