File: setcomp.pyx

package info (click to toggle)
cython 3.0.11%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 19,092 kB
  • sloc: python: 83,539; ansic: 18,831; cpp: 1,402; xml: 1,031; javascript: 511; makefile: 403; sh: 204; sed: 11
file content (64 lines) | stat: -rw-r--r-- 1,263 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

cimport cython

# Py2.3 doesn't have the set type, but Cython does :)
_set = set

def setcomp():
    """
    >>> type(setcomp()) is not list
    True
    >>> type(setcomp()) is _set
    True
    >>> sorted(setcomp())
    [0, 4, 8]
    """
    x = 'abc'
    result = { x*2
             for x in range(5)
             if x % 2 == 0 }
    assert x == 'abc' # do not leak
    return result

@cython.test_assert_path_exists(
    "//InlinedGeneratorExpressionNode",
    "//ComprehensionAppendNode")
def genexp_set():
    """
    >>> type(genexp_set()) is _set
    True
    >>> sorted(genexp_set())
    [0, 4, 8]
    """
    x = 'abc'
    result = set( x*2
                  for x in range(5)
                  if x % 2 == 0 )
    assert x == 'abc' # do not leak
    return result

cdef class A:
    def __repr__(self): return u"A"
    def __richcmp__(one, other, int op): return one is other
    def __hash__(self): return id(self) % 65536

def typed():
    """
    >>> list(typed())
    [A, A, A]
    """
    cdef A obj
    return {obj for obj in {A(), A(), A()}}

def iterdict():
    """
    >>> sorted(iterdict())
    [1, 2, 3]
    """
    cdef dict d = dict(a=1,b=2,c=3)
    return {d[key] for key in d}

def sorted(it):
    l = list(it)
    l.sort()
    return l