List slice assignment and custom sequences

Emile van Sebille emile at fenx.com
Sun Nov 3 02:12:05 EST 2002


Ronald Oussoren
> Sure, but xrange was just an example. FYI the actual type is NSArray
> (http://pyobjc.sourceforge.net). We'd like to make this type act as
> closely as possible like a normal list to avoid unnecessary
conversions
> to/from python types.
>

Well then, as a list won't do what you want, at least since object/class
unification you can get closer by shadowing list:



F:\Python22>python
ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on
Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import generators
>>> def xx():
...     for i in range(10):
...             yield i
...
>>>
>>> def listify(listwithiterables):
...     retval = []
...     from types import StringTypes
...     try:
...         for ii in listwithiterables:
...             if type(ii) in StringTypes:
...                 retval.append(ii)
...             else:
...                 try:
...                     retval.extend(ii)
...                 except:
...                     retval.append(ii)
...     except: pass
...     return retval
...
>>>
>>> class List(list):
...     setslice = list.__setslice__
...     def __setslice__(self, beg, end, iterobj):
...         List.setslice(self, beg, end, listify(iterobj))
...
>>>
>>> list=List
>>>
>>> l = list((1,2,3,4))
>>>
>>> l[1:3] = xrange(10)
>>> l[6:10] = xx()
>>>
>>> print l
[1, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 4]
>>>
>>> l = [1,2,3]
>>> l[:]=xx()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: must assign list (not "generator") to slice
>>> l = list(l)
>>> l[:]=xx()
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

--

Emile van Sebille
emile at fenx.com

---------







More information about the Python-list mailing list