mardi 7 novembre 2023

Inspecting recursive function with decorator fails only in Unittest

I have a recursive function that I would like to decorate. This decorator uses inspect.getclosurevars. The decorator fails and raises ValueError: cell is empty but only when used on functions definied in Unittest. When used outside they work as expected, where the recursive function is part of getclosurevars.unbound.

Minimal example:

import inspect
def deco(f):
    v = inspect.getclosurevars(f)
    print(v)
    return f

@deco # does not error
def recursive(n):
    if n <= 0 : return n
    return recursive(n-1)

import unittest
class TestA(unittest.TestCase):

    def test_but_in_unittest(self):
        
        @deco # ValueError: cell is empty
        def another_recursive(n):
            if n <= 0: return n
            return another_recursive(n-1)


unittest.main()

I’m really at a loss, initially I thought it was common for all recursive functions, but after some more testing and asking, I realized the error was occurring only within the test case.

I would normally expect the unittest testcase to behave the same as if it was ‘plain code’…





Aucun commentaire:

Enregistrer un commentaire