LibCST/libcst/_helpers.py
Jennifer Taylor ff65afaa26 Add a best practices section with various recommended practices.
There are going to be many more where this comes from, but these are the three cases that have come up most frequently, so I started with these. Hopefully this helps give additional direction to people using LibCST.
2019-10-23 16:50:47 -07:00

26 lines
970 B
Python

# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from typing import Type
from libcst._visitors import CSTNodeT
def ensure_type(node: object, nodetype: Type[CSTNodeT]) -> CSTNodeT:
"""
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__} bot got a {node.__class__.__name__}!"
)
return node