On this page
torch.jit.annotate
- torch.jit.annotate(the_type, the_value)[source]
- 
    This method is a pass-through function that returns the_value, used to hint TorchScript compiler the type ofthe_value. It is a no-op when running outside of TorchScript.Though TorchScript can infer correct type for most Python expressions, there are some cases where type inference can be wrong, including: - Empty containers like []and{}, which TorchScript assumes to be container ofTensor
- Optional types like Optional[T]but assigned a valid value of typeT, TorchScript would assume it is typeTrather thanOptional[T]
 Note that annotate()does not help in__init__method oftorch.nn.Modulesubclasses because it is executed in eager mode. To annotate types oftorch.nn.Moduleattributes, useAnnotate()instead.Example: import torch from typing import Dict @torch.jit.script def fn(): # Telling TorchScript that this empty dictionary is a (str -> int) dictionary # instead of default dictionary type of (str -> Tensor). d = torch.jit.annotate(Dict[str, int], {}) # Without `torch.jit.annotate` above, following statement would fail because of # type mismatch. d["name"] = 20- Parameters
- 
      - the_type – Python type that should be passed to TorchScript compiler as type hint for the_value
- the_value – Value or expression to hint type for.
 
- the_type – Python type that should be passed to TorchScript compiler as type hint for 
- Returns
- 
      the_valueis passed back as return value.
 
- Empty containers like 
© 2024, PyTorch Contributors
PyTorch has a BSD-style license, as found in the LICENSE file.
 https://pytorch.org/docs/2.1/generated/torch.jit.annotate.html