sourcery_analytics.utils

Functions that don’t fit anywhere else.

sourcery_analytics.utils.clean_source(source_str: str) str

Removes whitespace surrounding a source code string.

Examples

>>> source = '''
...
...     def example():
...         return "have a nice day"
... '''
>>> clean_source(source)
'def example():\n    return "have a nice day"'
sourcery_analytics.utils.nodedispatch(node_function: Callable[[N], T]) Callable[[Union[str, NodeNG, Path]], T]

Extends compatibility of functions over nodes.

Converts a function from working only on nodes to working on strings, nodes, and file paths.

Examples

>>> @nodedispatch
... def node_type(node):
...     return node.__class__
>>> node_type("x")
<class 'astroid.nodes.node_classes.Name'>
exception sourcery_analytics.utils.InvalidNodeTypeError

Bases: ValueError

Raised when a node’s type is validated and found to be incorrect.

sourcery_analytics.utils.validate_node_type(*types: Type[NodeNG])

Wraps any node function and validates the node’s type.

Parameters

*types – any subclasses of astroid.nodes.NodeNG

Raises

InvalidNodeTypeError – If the passed node doesn’t match one of the allowed types.

Examples

>>> @validate_node_type(astroid.nodes.Const)
... def is_int(node: astroid.nodes.Const):
...     return isinstance(node.value, int)
>>> expr = astroid.extract_node('5 + 4')
>>> is_int(expr.left)
True
>>> is_int(expr)
Traceback (most recent call last):
sourcery_analytics.utils.InvalidNodeTypeError...