Skip to content

[jit] support isinstance(foo, dict) #37516

@suo

Description

@suo

Today doing something like:

@torch.jit.script
def foo(s: Any):
    if isinstance(s, dict):
        print(s.items())

gives:

RuntimeError: Unknown type name 'dict':

And capitalizing "dict" will produce a segfault. Yikes!

A related issue is that doing something like:

isinstance(foo, Dict[str, Tensor])

is not actually possible in Python, since the type annotations are mostly static constructs that the interpreter doesn't know anything about.

A potential compromise is to have isinstance(foo, dict) refine the type of foo to Dict[Any, Any]. And then the user can further type refine to get an actual things they want. So:

if isinstance(foo, dict):
    for k, v in foo.items():
        assert isinstance(k, str)
        assert isinstance(v, Tensor)

Another potential solution is to have a torch.jit.isinstance(foo, Dict[str, tensor]) that boils down to isinstance(foo, dict) in Python but performs the correct type refinement in TS.

cc @suo @gmagogsfm

Metadata

Metadata

Assignees

Labels

daysenhancementNot as big of a feature, but technically not a bug. Should be easy to fixmodule: bootcampWe plan to do a full writeup on the issue, and then get someone to do it for onboardingoncall: jitAdd this issue/PR to JIT oncall triage queuetriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions