Skip to main content

Attributes as Functions

Object attributes can be exposed as Dagger Functions, without having to create a getter function explicitly.

There's a dagger.field descriptor that is a wrapper of dataclasses.field, but creates a getter function for the attribute as well so that it's accessible from the Dagger API.

Here's an example where one attribute is exposed as a function, while the other is not:

"""An example exposing Dagger Functions for object attributes."""
from typing import Annotated

from dagger import Doc, field, function, object_type


@object_type
class MyModule:
"""Functions for greeting the world"""

greeting: Annotated[str, Doc("The greeting to use")] = field(default="Hello")
name: Annotated[str, Doc("Who to greet")] = "World"

@function
def message(self) -> str:
"""Return the greeting message"""
return f"{self.greeting}, {self.name}!"

Notice that compared to dataclasses.field, the dagger.field wrapper only supports setting init: bool, and both default and default_factory in the same default parameter.

Confirm with dagger call --help that only the greeting function was created, with name remaining only a constructor argument:

Flags:
--greeting string The greeting to use (default "Hello")
--name string Who to greet (default "World")

Function Commands:
greeting The greeting to use
message Return the greeting message
note

In a future version of the Python SDK, the same dagger.function decorator will be used as a descriptor in place of dagger.field to make the distinction clearer.