Is there a way to get a type from a function that takes a string for an argument?

Viewed 53

I have a function that takes a single string arg.

I think in my first post of this issue I was not clear enought.

The purpose of this question is to figure how how to get typing (autocomplete) support for such methods without using cast.

doc = CreateScritpService("Calc")

To get the type I use cast.

doc = cast(SFDocuments.SF_Calc, CreateScritpService("Calc"))

bas = cast(SFScriptForge.SF_Basic, CreateScriptService("Basic"))

I am the Author of ScriptForge Typings

An I am looking for a way to automatically have CreateScritpService return the correct type based upon the string input arg. Is this possible?

1 Answers

You can achieve this using overload along with Literal, something like this:

from typing import Literal, overload

@overload
def CreateScriptService(x: Literal["Calc"]) -> SFDocuments.SF_Calc:
    ...

@overload
def CreateScriptService(x: Literal["Basic"]) -> SFScriptForge.SF_Basic:
    ...
Related