traits
traits copied to clipboard
Issues with typing of `BaseInstance`
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.