Use Literal[] strings in an overload python

Viewed 166

I have a factory function taking a string and returning different objects based on that - e.g.

def get_object(clsid:str) -> object:
    if clsid == "Foo":
        return Foo()
    elif clsid == "Bar":
        return Bar()
    elif ...

That's pseudocode - in reality I'm using win32com EnsureDispatch to get a com object from its clsid

I want to use mypy's Literal type to say if clsid is "Foo" then Foo type will be returned, otherwise default to object. However I tried:

@overload
def get_object(clsid:Literal["Foo"]) -> Foo: ...

def get_object(clsid:str) -> object:
    ... # concrete implementation

but what I really need is

@overload
def get_object(clsid:str AND NOT (Literal["Foo"] | Literal["Bar"]) ) -> object: ...
@overload
def get_object(clsid:Literal["Foo"]) -> Foo: ...
@overload
def get_object(clsid:Literal["Bar"]) -> Bar: ...
def get_object(clsid:str) -> object: #concrete

I guess I could make the concrete only accept Literal["Foo"]|Literal["Bar"] and then add more options as I need them rather than accepting all strs but IDK what's idiomatic here?

0 Answers
Related