Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to proxy a Python str and make join work?

Tags:

python

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?

like image 398
uranusjr Avatar asked Dec 14 '13 12:12

uranusjr


1 Answers

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.

like image 61
user2357112 supports Monica Avatar answered Oct 07 '22 23:10

user2357112 supports Monica