Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In Python, can typings define a property added to a function?

Example, I have some Redux helpers that are functions, but those functions also define a `.actionType` property. TypeScript handles that.

edit: accidentally wrote "object" instead of "function"



The typical approach to this in Python is to define a callable class instead. If you define the __call__() method on a class, instances of the class will be callable.

  class IntAdder:

      def __init__(self, x: int) -> None:
          self.x = x

      def __call__(self, y: int) -> int:
          return self.x + y

      def __str__(self) -> str:
          return f"({self.x} + ??)"

  add1 = IntAdder(1)
  assert add1(3) == 4
  print(add1)
  # (1 + ??)
As mentioned in the sibling comment, you can define a Protocol which is analogous to an interface, so if you had a protocol like this:

  from typing import Protocol, TypeVar

  T = TypeVar("T")

  class ValueUpdater(Protocol[T]):
      def __call__(self, y: T) -> T: ...
Then IntAdder would be considered a subclass of ValueUpdater[int] by the type checker. Demo: https://mypy-play.net/?mypy=1.5.1&python=3.11&flags=strict&g...


I believe you could have a Protocol that requires the property and that the object is Callable.


Ah, that's not really that different than in TypeScript then. There you have to define a callable interface, and can add whatever properties you want

    interface SomethingCallableWithAnExtraProperty {
      // This means you can call it like a function.
      (args: Whatever): SomethingReturned

      // And since it's an interface, you can still do interface-y things
      anotherProperty: string
    }




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: