Can a function be a Python dataclass member?

Viewed 3438

I'm trying to keep some functions together and tried a Python dataclass for this. I could not come up with or find how to assign a type to a function within a dataclass.

In example below I used a dummy type int, but what I should use correctly instead of int?

from dataclasses import dataclass

inc = lambda x : x+1

@dataclass
class Holder:
  func: int # but I need a better type signature here

h = Holder(inc)

assert h.func(1) == 2
1 Answers

You should use the Callable type

from typing import Callable

@dataclass
class Holder:
  func: Callable[[int], int]
Related