1# Copyright (c) Meta Platforms, Inc. and affiliates.
2#
3# This source code is licensed under the MIT license found in the
4# LICENSE file in the root directory of this source tree.
5#
6from typing import Type, TypeVar
7
8T = TypeVar("T")
9
10
11def ensure_type(node: object, nodetype: Type[T]) -> T:
12 """
13 Takes any python object, and a LibCST :class:`~libcst.CSTNode` subclass and
14 refines the type of the python object. This is most useful when you already
15 know that a particular object is a certain type but your type checker is not
16 convinced. Note that this does an instance check for you and raises an
17 exception if it is not the right type, so this should be used in situations
18 where you are sure of the type given previous checks.
19 """
20
21 if not isinstance(node, nodetype):
22 raise ValueError(
23 f"Expected a {nodetype.__name__} but got a {node.__class__.__qualname__}!"
24 )
25 return node