#Is it possible to use polymorphism in a dagger function return type?

1 messages · Page 1 of 1 (latest)

brave summit
#

Hi there!!
I want to implement a dagger function in the python SDK where the dagger function return type is a base class and it returns a derived class that implements or modifies the base method.

  1. Abstract class implementation

Code example:

from abc import ABC, abstractmethod
import dagger

@dagger.object_type
class TestA(ABC):
    @dagger.function
    @abstractmethod
    def test(self) -> str: ...


@dagger.object_type
class TestI(TestA):
    @dagger.function
    def test(self) -> str:
        return "asd"


@dagger.object_type
class MyModule:
    """MyModule class."""

    @dagger.function
    def test(self) -> TestA:
        return TestI()

I'm calling the dagger cli like this: dagger call test test

I'm getting the following error which is quite explanatory: Failed to instantiate TestA: invalid type (Can't instantiate abstract class TestA without an implementation for abstract method 'test')

  1. Derived class

Code example:

@dagger.object_type
class TestA:
    @dagger.function
    def test(self) -> str:
        return "test_a"


@dagger.object_type
class TestI(TestA):
    @dagger.function
    def test(self) -> str:
        test_a = super().test()
        return test_a + "-" + "test_i"


@dagger.object_type
class MyModule:
    """MyModule class."""

    @dagger.function
    def test(self) -> TestA:
        return TestI()

I'm calling the dagger cli like this: dagger call test test

It's returning test_a instead of test_a-test_i

Is it possible to set in a @dagger.function a return base class or protocol and return a derived class in the implementation?

#

dagger function return type base class

brave summit
#

Is it possible to use polymorphism in a dagger function return type?

true knot
#

@brave summit Dagger's type system has interfaces (based on graphql interfaces under the hood). Not sure if they're supported in the Python SDK yet. cc @placid jay @fallen sigil

placid jay
#

The reason what you have doesn't work is that during serialization the Python SDK sees that the type that MyModule.test returns is TestA so it instantiates that. When TestI() is returned, the type it came from isn't persisted, only its state. But https://docs.dagger.io/api/interfaces will do what you want.