audeering / audobject

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

What to do if a callable object is passed instead of a function #28

Closed frankenjoe closed 2 years ago

frankenjoe commented 2 years ago

Since a callable function looks like a function, a user may try the following:

class MyCallableObject:
    def __call__(self, x):
        return x * x

func = MyCallableObject()

class MyObjectWithFunction(audobject.Object):

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

    def __call__(self, x):
        return self.func(x)

o = MyObjectWithFunction(func)
o(3)
9

However, trying to serialize o fails:

audobject.from_yaml_s(o.to_yaml_s())
AttributeError: 'MyCallableObject' object has no attribute '__name__'

Generally, there is no solution for this and we should raise a proper error saying it's not possible to serialize a callable object.

However, there is an exception where it should be possible and that is when it derives from Object, i.e.:

class MyCallableObject(audobject.Object):
    def __call__(self, x):
        return x * x

In that case we can simply dump the YAML representation of the object, which will allow us to recreate the object later on.