How to annotate a variable referring to an already defined function? #1038
-
I ran into this while using the xmlschema package, so I will use it as an example. However the question could concern any def decode(
self,
source: Union[XMLSourceType, XMLResource],
path: Optional[str] = None,
schema_path: Optional[str] = None,
validation: str = "strict",
*args: Any,
**kwargs: Any
) -> DecodeType[Any]: ... this function is also reference by another variable creating an alias or a pointer to that function: to_dict = decode The package is a I was looking into DecodeFuncType = Callable[
[Union[XMLSourceType, XMLResource], str | None, str | None, str, Any, Any],
DecodeType[Any],
]
to_dict: DecodeFuncType = decode which follows the original function signature, I get limited completion, cannot use keyword arguments and typechecker complains about missing positional arguments. Also this is much more clunky when the function is already defined using the standard function annotation without Callable.
Steps to reproduce:
import xmlschema
xsd = xmlschema.XMLSchema("some_schema.xsd")
xml_dict = xsd.to_dict("some_xml.xml") # Pylance complains that `to_dict()` is Unknown and no code completion is provided
xml_decoded = xsd.decode("some_xml.xml") # This is ok and code completion is provided |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
There’s two ways you can annotate this. First you could just duplicate the function definition under the second name. Secondly, if you do want to specify it as more of a global variable that may be changed, you can use a |
Beta Was this translation helpful? Give feedback.
There’s two ways you can annotate this. First you could just duplicate the function definition under the second name. Secondly, if you do want to specify it as more of a global variable that may be changed, you can use a
Protocol
containing only a__call__
method as effectively an advancedCallable
type.