0

I have a case where I would like to defeat string interning.

Let's say the string I have is "foo bar".

I know of a few hacky/not obvious ways to defeat interning a string. All involve computing the expression at runtime.

In [1]: my_str = "foo bar"
In [2]: my_new_str1 = " ".join(["foo", "bar"])
In [3]: my_new_str2 = "foo bar "[:-1]
In [4]: my_new_str3 = "foo " + "bar"

In [5]: id(my_str)
Out[5]: 4483028144

In [6]: id(my_new_str1)
Out[6]: 4483030192

In [7]: id(my_new_str2)
Out[7]: 4484125872

In [8]: id(my_new_str3)
Out[8]: 4484052336

There is a built-in function sys.intern, which interns a string. I am looking to do the exact opposite, not intern something in a simple/descriptive way.

Is there anything out there that can defeat string interning in a "clean" way?

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119

2 Answers2

3

I suppose put a function around join:

def new_str(s):
    return ''.join(s)

>>> s='a string'

>>> s1=new_str(s)

>>> id(s)
4568404208

>>> id(s1)
4569455664

>>> s is s1
False

But I think this is silly...

dawg
  • 98,345
  • 23
  • 131
  • 206
  • Yes thank you @dawg for the answer. In the OP, I already included `.join` as one method. I was wondering if there's a more descriptive/meaningful way. I would prefer not to add a utility function `new_str` to my client code, even though it's not many lines of code – Intrastellar Explorer May 19 '21 at 02:36
  • *Descriptive* and *meaningful* are in the eye of the beholder. What is descriptive and meaningful to you? – dawg May 19 '21 at 02:38
2

You could also subclass str.

>>> class UninternedStr(str):
...   pass
... 
>>> s = UninternedStr('a string')
>>> s1 = UninternedStr('a string')
>>> s is s1
False
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116