audeering / audobject

Generic Python interface for serializing objects to YAML
https://audeering.github.io/audobject/
Other
1 stars 0 forks source link

OSError: could not get source code #22

Closed frankenjoe closed 2 years ago

frankenjoe commented 2 years ago

When we want to serialize a function we use inspect.getsource(func) to get the source code of the function. This, however, fails for dynamically defined functions. Consequently, we get an error if we try to serialize the function of an object that has already been loaded from YAML:

class MyObjectWithFunction(audobject.Object):

    @audobject.init_decorator(
        resolvers={
            'func': audobject.resolver.Function,
        }
    )
    def __init__(
            self,
            func: typing.Callable,
    ):
        self.func = func

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

def add(a, b):
    return a + b

o = MyObjectWithFunction(add)
o_yaml = o.to_yaml_s()
o2 = audobject.from_yaml_s(o_yaml)

# cannot inspect code of a dynamically defined function
o2.to_yaml_s(s)
OSError: could not get source code