I'm trying to implement a lazy-evaluated str-like class. What I have now is simething like
class LazyString(object):
__class__ = str
def __init__(self, func):
self._func = func
def __str__(self):
return self._func()
which works fine (for my purposes) in most cases, except one: str.join
:
' '.join(['this', LazyString(lambda: 'works')])
fails with
TypeError: sequence item 1: expected string, LazyString found
And after some poking around there doesn't seem to be any magic functions available behind this. join
seems to be hard-coded inside the core implementation, and only instances of limited built-in type can make it work without actually being a str
.
So am I really out of options here, or is there another way that I'm not aware of?
join
takes strings, so give it strings:
' '.join(map(str, ['this', LazyString(lambda: 'works')]))
Python does not have support for the kind of transparent lazy evaluation you're looking for. If you want to force evaluation of a lazy object, you will have to do so explicitly, rather than having it done automatically when needed. Sometimes, Python will call some method of your object that you can rely on, such as __nonzero__
if you want a lazy boolean, but not always, and you won't generally be able to achieve full interoperability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With