from __future__ import print_function, absolute_import
from numba.utils import OrderedDict
import numpy as np
from numba import njit
from numba.jitclass import jitclass
from numba import int32, deferred_type, optional
from numba.runtime import rtsys

node_type = deferred_type()

spec = OrderedDict()
spec['data'] = int32
spec['next'] = optional(node_type)


@jitclass(spec)
class LinkedNode(object):
    def __init__(self, data, next):
        self.data = data
        self.next = next

    def prepend(self, data):
        return LinkedNode(data, self)


@njit
def make_linked_node(data):
    return LinkedNode(data, None)


node_type.define(LinkedNode.class_type.instance_type)


@njit
def fill_array(arr):
    head = make_linked_node(0)
    for i in range(1, arr.size):
        head = head.prepend(i)

    c = 0
    while head is not None:
        arr[c] = head.data
        head = head.next
        c += 1


def runme():
    arr = np.zeros(100000, dtype=np.int32)
    fill_array(arr)

    # print(arr)


if __name__ == '__main__':
    runme()
    print(rtsys.get_allocation_stats())
    # Pure python: 104ms
    # jitclass: 2.23s
    # jitclass + make_linked_node: 2.15s
    # jitclass + make_linked_node + fill_array: 34.7ms

    # Pure python: 87.3ms
    # jitclass: 892ms
    # jitclass + make_linked_node: 871ms
    # jitclass + make_linked_node + fill_array: 36.1ms

@@ -1,12 +1,110 @@
+%22%22%22%0AThis example demonstrates jitclasses and deferred types for writing a%0Asingly-linked-list.%0A%22%22%22%0A
 from __futur
@@ -801,16 +801,245 @@
 y(arr):%0A
+    %22%22%22%0A    Fills the array with n, n - 1, n - 2 and so on%0A    First we populate a linked list with values 1 ... n%0A    Then, we traverse the the linked list in reverse and put the value%0A    into the array from the index.%0A    %22%22%22%0A
     head
@@ -1082,16 +1082,20 @@
 range(1,
+ 1 +
  arr.siz
@@ -1271,20 +1271,16 @@
 zeros(10
-0000
 , dtype=
@@ -1313,391 +1313,282 @@
 rr)%0A
-%0A
    
- #
  print(
-arr)%0A%0A%0Aif __name__ == '__main__':%0A    runme()%0A    print(rtsys.get_allocation_stats())%0A    # Pure python: 104ms%0A    # jitclass: 2.23s%0A    # jitclass + make_linked_node: 2.15s%0A    # jitclass + make_linked_node + fill_array: 34.7ms%0A%0A    # Pure python: 87.3ms%0A    # jitclass: 892ms%0A    # jitclass + make_linked_node: 871ms%0A    # jitclass + make_linked_node + fill_array: 36.1ms
+%22== Result ==%22)%0A    print(arr)%0A    # Check answer%0A    np.testing.assert_equal(arr, 1 + np.arange(arr.size, dtype=arr.dtype)%5B::-1%5D)%0A%0A%0Aif __name__ == '__main__':%0A    runme()%0A    print(%22== Print memory allocation information == %22)%0A    print(rtsys.get_allocation_stats())
 %0A

Add comments to linkedlist example