Question Details

No question body available.

Tags

python python-typing typing

Answers (3)

March 20, 2026 Score: 1 Rep: 452 Quality: Low Completeness: 60%

I found a hack while looking at the source code of UserString. You could do something like this:

from collections import UserString
from functools import cachedproperty

def double(s): print('Computing...') return s + s

class LazyString(UserString): # Specify slots to make the class usable as a dict key slots = ('originalstr',)

# No good very bad hack, but it works class = str

def init(self, originalstr: str): self.originalstr = originalstr

# cachedproperty so that double is called only once @cachedproperty def data(self) -> str: return double(self.originalstr)

s = LazyString("test")

Then,

>>> s # Lzay computation here, repr is called
Computing...
'testtest'

>>> print(s) # str is called testtest

>>> isinstance(s, str) # Check passed True

>>> {s: 1} # Can be used a dict key {'testtest': 1}

>>> len(s) # len ok 8

>>> s[5] # Indexation ok 'e'

This should work for the few use-cases you described, though there is probably an edge case that breaks everything, as per usual.

Disclaimer: any new string created from using a method (or indexing) LazyString will be an str, not a LazyString. This is better since it prevent issues with doubling down on the custom functions call.

March 20, 2026 Score: 0 Rep: 550,075 Quality: Low Completeness: 40%

Depending on what OP wants, this approach doesn’t really work. For example, len(s) returns 4, and s[4] causes an IndexError (for all practical purposes I’d expect the results 8 and 't', respectively).

March 20, 2026 Score: 0 Rep: 452 Quality: Low Completeness: 0%

That's fair, though I'd say OP posted their requirements. I'll change my answer real quick.