これは、Python での文字列インターンに関する以前の質問のフォローアップですが、別の質問として認定するのに十分な関連性はないと思います。要するに、sys.intern を使用する場合、ほとんど/すべての使用時に問題の文字列を関数に渡す必要がありますか、それとも文字列を一度だけインターンしてその参照を追跡する必要がありますか? 私が正しいと思うことを行う疑似コード的なユースケースで明確にするために:(コメントを参照)
# stores all words in sequence,
# we want duplicate words too,
# but those should refer to the same string
# (the reason we want interning)
word_sequence = []
# simple word count dictionary
word_dictionary = {}
for line in text:
for word in line: # using magic unspecified parsing/tokenizing logic
# returns a canonical "reference"
word_i = sys.intern(word)
word_sequence.append(word_i)
try:
# do not need to intern again for
# specific use as dictonary key,
# or is something undesirable done
# by the dictionary that would require
# another call here?
word_dictionary[word_i] += 1
except KeyError:
word_dictionary[word_i] = 1
# ...somewhere else in a function far away...
# Let's say that we want to use the word sequence list to
# access the dictionary (even the duplicates):
for word in word_sequence:
# Do NOT need to re-sys.intern() word
# because it is the same string object
# interned previously?
count = word_dictionary[word]
print(count)
別の辞書の単語にアクセスしたい場合はどうすればよいですか? キーがすでにインターンされている場合でも、key:value を挿入するときに sys.intern() を再度使用する必要がありますか? 説明がありますか?前もって感謝します。