Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issues with typing of BaseInstance #1764

Open
corranwebster opened this issue Jan 26, 2024 · 1 comment
Open

Issues with typing of BaseInstance #1764

corranwebster opened this issue Jan 26, 2024 · 1 comment

Comments

@corranwebster
Copy link
Contributor

corranwebster commented Jan 26, 2024

The definition of BaseInstance in trait_types.pyi looks like this:

class _BaseInstance(_BaseClass[_T]):
# simplified signature
def __init__(
self,
klass: _T,
*args: _Any,
**metadata: _Any,
) -> None:
...

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
Copy link
Contributor Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant