File: common.py

package info (click to toggle)
python-libcst 1.4.0-1.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 5,928 kB
  • sloc: python: 76,235; makefile: 10; sh: 2
file content (25 lines) | stat: -rw-r--r-- 933 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from typing import Type, TypeVar

T = TypeVar("T")


def ensure_type(node: object, nodetype: Type[T]) -> T:
    """
    Takes any python object, and a LibCST :class:`~libcst.CSTNode` subclass and
    refines the type of the python object. This is most useful when you already
    know that a particular object is a certain type but your type checker is not
    convinced. Note that this does an instance check for you and raises an
    exception if it is not the right type, so this should be used in situations
    where you are sure of the type given previous checks.
    """

    if not isinstance(node, nodetype):
        raise Exception(
            f"Expected a {nodetype.__name__} but got a {node.__class__.__name__}!"
        )
    return node