Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function be a Python dataclass member?

Tags:

python

types

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
like image 821
Evgeny Avatar asked Feb 24 '26 15:02

Evgeny


1 Answers

You should use the Callable type

from typing import Callable

@dataclass
class Holder:
  func: Callable[[int], int]
like image 110
rdas Avatar answered Feb 26 '26 06:02

rdas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!