#python sdk : how to use chaining with __init__ ?

1 messages · Page 1 of 1 (latest)

dapper flint
#

Hi there. assume the python module code below :

@object_type
class MyModule:
    def __init__(self, version: str | None = None) -> None:
        # initialize base environment
        self.ctr = (
            dag.container()
            .from_("python:3.11-bookworm")
            # ... 
        )
    
    @function
    def with_config(self, config: str) -> Self:
        # chain some config ...
        return self

Which I call like so:

dagger call -m my-module --version="1.3.0" --with-config some-config

This approach does not seem to work. Is this the proper way to passing argument to initialize the base container?

quaint escarp
#

if you call dagger functions, that should show you with-config

#

so i think what you're looking for is dagger call with-config --config=value

quaint escarp
#
import dataclasses
import dagger
from dagger import dag, function, object_type, field

# NOTE: it's recommended to move your code into other files in this package
# and keep __init__.py for imports only, according to Python's convention.
# The only requirement is that Dagger needs to be able to import a package
# called "main", so as long as the files are imported here, they should be
# available to Dagger.


@object_type
class PythonSpikes:

    base: dagger.Container = field(init=False)    
    version: dataclasses.InitVar[str] = "3.11-bookworm"

    config: str = field(default="default value", init=False)

    def __post_init__(self, version: str):
        self.base = dag.container().from_(f"python:{version}")
        

    @function
    def with_config(self, config: str) -> "PythonSpikes":
        self.config = config
        return self
    
    @function
    async def echo(self) -> str:        
        return await self.base.with_exec(["sh", "-c", f"echo '{self.config} from os..' && cat /etc/os-release"]).stdout()
        

this could be called like this:

dagger -m .\dagger-python-spikes\ call --version=3.10-bookworm with-config --config "hello" echo

This gives me this output:

hello from os..
PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
NAME="Debian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

I took some material from here: https://docs.dagger.io/manuals/developer/entrypoint-function#constructor-only-arguments

Every Dagger module has an entrypoint function. The default one is generated automatically and has no arguments.

night berry