开发者

Uniq id function in python or not?

开发者 https://www.devze.com 2023-03-16 04:26 出处:网络
I have several python scripts run parallel this simple code: test_id = id(\'test\') 开发者_开发百科Is test_id unique or not?http://docs.python.org/library/functions.html#id

I have several python scripts run parallel this simple code:

test_id = id('test')

开发者_开发百科Is test_id unique or not?


http://docs.python.org/library/functions.html#id

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object.

So yes, the IDs are unique.

However, since Python strings are immutable, id('test') may be the same for all strings since 'test' is 'test' is likely to be True.


What do you mean unique? Unique among what?

It is just identifier for part of memory, used by parameter's value. For immutable objects with the same value it is often the same:

>>> id('foo') == id('fo' + 'o')
True


In CPython, id is the pointer to the object in memory.

>>> a = [1,2,3]
>>> b = a
>>> id(a) == id(b)
True

So, if you have multiple references to the same object (and on some corner cases, small strings are created only once and also numbers smaller than 257) it will not be unique


It might help if you talked about what you were trying to do - it isn't really typical to use the id() builtin for anything, least of all strings, unless you really know what you're doing.

Python docs nicely describe the id() builtin function:

This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

As I read this, the return values of id() are really only guaranteed to be unique in one interpreter instance - and even then only if the lifetimes of the items overlap. Saving these ids for later use, sending them over sockets, etc. seems not useful. Again, I don't think this is really for people who don't know that they need it.

If you want to generate IDs which are unique across multiple program instances, you might check out the uuid module.

It also occurs to me that you might be trying to produce hashes from Python objects.

Probably there is some approach to your problem which will be cleaner than trying to use the id() function, maybe the problem needs reformulating.

0

精彩评论

暂无评论...
验证码 换一张
取 消