Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, lazy list

Is it possible to have a list be evaluated lazily in Python?

For example

a = 1
list = [a]
print list
#[1]
a = 2
print list
#[1]

If the list was set to evaluate lazily then the final line would be [2]

like image 417
Mike Avatar asked Mar 08 '10 03:03

Mike


2 Answers

Python is not really very lazy in general.

You can use generators to emulate lazy data structures (like infinite lists, et cetera), but as far as things like using normal list syntax, et cetera, you're not going to have laziness.

like image 121
Amber Avatar answered Oct 29 '22 05:10

Amber


Came across this post when looking for a genuine lazy list implementation, but it sounded like a fun thing to try and work out.

The following implementation does basically what was originally asked for:

from collections import Sequence

class LazyClosureSequence(Sequence):
    def __init__(self, get_items):
        self._get_items = get_items

    def __getitem__(self, i):
        return self._get_items()[i]

    def __len__(self):
        return len(self._get_items())

    def __repr__(self):
        return repr(self._get_items())

You use it like this:

>>> a = 1
>>> l = LazyClosureSequence(lambda: [a])
>>> print l
[1]
>>> a = 2
>>> print l
[2]

This is obviously horrible.

like image 39
Jamie Cockburn Avatar answered Oct 29 '22 04:10

Jamie Cockburn