Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

language features - Python intern for non-strings

Why is Python's intern built-in only for strings? It should be possible to extend intern to classes that are hashable and comparable, right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The purpose of interning things is to be able to compare them by comparing their memory address; you ensure that you never create two objects with the same value (when the program requests the creation of a second object with the same value as an existing object, it instead receives a reference to the pre-existing object). This requires that the things you're interning be immutable; if the value of an interned object could change, comparing them by address isn't going to work.

In Python, it's not possible to enforce the immutability of user-defined class instances, so it wouldn't be safe to intern them. I suspect that's the main theoretical reason intern doesn't cover class instances.

Other built in immutable types are either comparable in a single machine-level operation already (int, float, etc), or immutable containers that can contain mutable values (tuple, frozenset). There's no need to intern the former, and the latter can't be safely interned either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...