|
| 1 | +// Copyright 2018 The go-python Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package py |
| 6 | + |
| 7 | +// A python Zip object |
| 8 | +type Zip struct { |
| 9 | + itTuple Tuple |
| 10 | + size int |
| 11 | +} |
| 12 | + |
| 13 | +// A python ZipIterator iterator |
| 14 | +type ZipIterator struct { |
| 15 | + zip Zip |
| 16 | +} |
| 17 | + |
| 18 | +var ZipType = NewTypeX("zip", `zip(iter1 [,iter2 [...]]) --> zip object |
| 19 | +
|
| 20 | +Return a zip object whose .__next__() method returns a tuple where |
| 21 | +the i-th element comes from the i-th iterable argument. The .__next__() |
| 22 | +method continues until the shortest iterable in the argument sequence |
| 23 | +is exhausted and then it raises StopIteration.`, |
| 24 | + ZipTypeNew, nil) |
| 25 | + |
| 26 | +// Type of this object |
| 27 | +func (z *Zip) Type() *Type { |
| 28 | + return ZipType |
| 29 | +} |
| 30 | + |
| 31 | +// ZipTypeNew |
| 32 | +func ZipTypeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error) { |
| 33 | + tupleSize := len(args) |
| 34 | + itTuple := make(Tuple, tupleSize) |
| 35 | + for i := 0; i < tupleSize; i++ { |
| 36 | + item := args[i] |
| 37 | + iter, err := Iter(item) |
| 38 | + if err != nil { |
| 39 | + return nil, ExceptionNewf(TypeError, "zip argument #%d must support iteration", i+1) |
| 40 | + } |
| 41 | + itTuple[i] = iter |
| 42 | + } |
| 43 | + |
| 44 | + return &Zip{itTuple: itTuple, size: tupleSize}, nil |
| 45 | +} |
| 46 | + |
| 47 | +// Zip iterator |
| 48 | +func (z *Zip) M__iter__() (Object, error) { |
| 49 | + return z, nil |
| 50 | +} |
| 51 | + |
| 52 | +func (z *Zip) M__next__() (Object, error) { |
| 53 | + result := make(Tuple, z.size) |
| 54 | + for i := 0; i < z.size; i++ { |
| 55 | + value, err := Next(z.itTuple[i]) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + result[i] = value |
| 60 | + } |
| 61 | + return result, nil |
| 62 | +} |
| 63 | + |
| 64 | +// Check interface is satisfied |
| 65 | +var _ I__iter__ = (*Zip)(nil) |
| 66 | +var _ I__next__ = (*Zip)(nil) |
0 commit comments