Python Forum

Full Version: how to type hint a function in a dataclass?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wish to create a dataclass where one of the attributes will hold a function. It could be any function, so I won't know what parameters it will accept when the dataclass is used.

I see that python doesn't do strict typing, so the following code will work, but it technically is not correct. What is the correct way to declare my task attribute to be a function?

from dataclasses import dataclass

@dataclass
class Schedule:
    name: str
    task: str       # <--- what should this be?
    interval: int
    
    
def hello(name=None):
    print(f"Hello {name}!")


def hello2(name, age):
    print(f"Hello {name}! You are {age} years old.")
    

job1 = Schedule("Greeter", hello, 5)
print(job1)
print(job1.name)
job1.task("Bob")

job2 = Schedule("Age", hello2, 1)
job2.task("Bob", 22)
from collections.abc import Callable
from dataclasses import dataclass


@dataclass
class Schedule:
    name: str
    task: Callable
    interval: int
Or if you want to be more specific you can type task as a function that takes a str and returns None
@dataclass
class Schedule:
    name: str
    task: Callable[[str], None]
    interval: int
Since you don't know the exact signature of the function beforehand,
you can specify it to accept any parameters and return any type using Callable[..., Any]
from dataclasses import dataclass
from typing import Callable, Any

@dataclass
class Schedule:
    name: str
    # Correct type for a function with any signature
    task: Callable[..., Any]
    interval: int

def hello(name=None):
    print(f"Hello {name}!")

def hello2(name, age):
    print(f"Hello {name}! You are {age} years old.")

job1 = Schedule("Greeter", hello, 5)
print(job1)
print(job1.name)
job1.task("Bob")

job2 = Schedule("Age", hello2, 1)
job2.task("Bob", 22)
Thanks for the replies guys... For some reason I'm not getting email notifications when someone replies.

These are good answers, but my methodology wasn't sound. I need to pass this data to Ray functions and these "callable" variables won't pickle.