Are nested functions unsupported?

My MWE is:

@njit
 def solve(n):
     count = np.zeros(n + 1, dtype=int)
     res = np.array([0], dtype=int)

     def search(sz=0, max_val=1, single=0, previous=None):
         nonlocal res
         if sz == 4 * n:
             res[0] += 1
             return
         if single and count[0] < 2 * n:
             count[0] += 1
             search(sz + 1, max_val, single)
             count[0] -= 1
         for i in range(1, max_val + 1):
             if i != previous and count[i] < 2:
                 count[i] += 1
                 search(sz + 1, max_val + (i == max_val and max_val < n), single + (count[i] == 1) - (count[i] == 2), i)
                 count[i] -= 1
 
     search()
     return res[0]

This gives me:

NotImplementedError: Failed in nopython mode pipeline (step: analyzing bytecode)
Unsupported use of op_LOAD_CLOSURE encountered

1 Like

https://numba.readthedocs.io/en/stable/reference/pysupported.html#functions

The reproducer lacks import statements and therefore isn’t self-contained. Making the script such that it can be copied and pasted into a Python file and run w/o modification will make it easier for folks to reproduce your issue.

Apologies, it should be:

from numba import njit
import numpy as np

@njit   
def solve(n):
    count = np.zeros(n + 1, dtype=int)
    res = np.array([0], dtype=int)

    def search(sz=0, max_val=1, single=0, previous=None):
        nonlocal res
        if sz == 4 * n:
            res[0] += 1
            return
        if single and count[0] < 2 * n:
            count[0] += 1
            search(sz + 1, max_val, single)
            count[0] -= 1
        for i in range(1, max_val + 1):
            if i != previous and count[i] < 2:
                count[i] += 1
                search(sz + 1, max_val + (i == max_val and max_val < n), single + (count[i] == 1) - (count[i] == 2), i)
                count[i] -= 1
 
    search()
    return res[0]

for i in range(1, 6):
    print(solve(i))

Question posted to python - How to handle Unsupported use of op_LOAD_CLOSURE encountered? - Stack Overflow .