enthought / traits

Observable typed attributes for Python classes
Other
421 stars 85 forks source link

Issues with typing of `BaseInstance` #1764

Open corranwebster opened 5 months ago

corranwebster commented 5 months ago

The definition of BaseInstance in trait_types.pyi looks like this: https://github.com/enthought/traits/blob/9778f4df710aaccf2a6680d3ce485fab2c196694/traits/trait_types.pyi#L512-L521

I think that this should read:

 class _BaseInstance(_TraitType[_Optional[_T], _Optional[_T]]):

    # simplified signature
    def __init__(
        self,
        klass: _Type[_T] | str,
        *args: _Any,
        **metadata: _Any,
    ) -> None:
        ...

since we're passing in a type or a str to the __init__ function (ignoring the corner case that Traits will accept Instance(foo) to mean Instance(type(foo)) since that is almost never used in declarative code), but the values are instances of the type or None (and never a string unless you do Instance(str), so the _TraitType[_Union[_T, str, None], [_Union[_T, str, None]] is wrong).

We have to allow str since that is a valid argument needed for forward definitions, but they leave the actual type unspecified; in those cases you can potentially explicitly define the type with a type declaration something like:

foo: Instance["Foo"] = Instance("Foo")

which should at least work for classes defined in the same module, or

foo: Instance[typing.Any] = Instance("foo.Foo")

for lazy instances.

In current code, this all gets plastered over because we then force _T to be Any in the concrete definition, but it means that tools like mypy can't infer the type from the definition so you are forced to do a lot of isinstance checks.

This is orthogonal to #1673 and solving this won't solve that.

corranwebster commented 4 months ago

A note that allowing the possibility of forward declarations with strings causes problems with inference in complex types. For example:

Dict(Instance(Foo), Instance(Bar))

can't be resolved as Dict[Foo, Bar, Foo, Bar] because the possibility of forward definitions can leave the type unclear even though we aren't using forward references.

This can be resolved by:

Dict(Instance[Foo](Foo), Instance[Bar](Bar))

but it is sort of awkward.