Home > Blockchain >  What is the right Python annotation for imported method as variable?
What is the right Python annotation for imported method as variable?

Time:01-20

I'm looking for a Method type that I could use to annotate improted instance methods, since Callable[[Self, ...], ...] doesn't works. Example:

mod_method.py

from __future__ import annotations

import typing

if typing.TYPE_CHECKING:
    from class import Object


def meth_method(self: Object, val: int) -> float:
    return val   10.5

class.py

from mod_method import meth_method


class Object:
    method: Method[[int], float] = meth_method

CodePudding user response:

meth_method is an ordinary function. An instance method in the sense you are thinking is just a function-valued class attribute. You get a method (of type types.MethodType) when you access the attribute via an instance of the class, thanks to the descriptor protocol.

As such, the correct type hint is types.FunctionType. (Not simply Callable, because it's types.FunctionType.__get__ that produces the bound method.)

class Object:
    method: types.FunctionType = meth_method

FunctionType is not generic the way Callable is, so unfortunately you cannot be more specific, like types.FunctionType[[Object, int], float].


As an aside, I would recommend against piecing a class definition together from functions defined outside the module. You may have an XY Problem that you are trying to solve.

CodePudding user response:

The correct Python annotation for imported method as a variable is:

@typing.overload
def varName(...) -> returnType:
    ...
  • Related