sourcery_analytics.metrics.working_memory

Working memory calculations.

The working memory is motivated by considering the number of pieces of information it is necessary to keep in mind while reading a piece of code. High working memory implies the code may have too many “moving parts” and could be simplified. The implementation of the calculation is described in the classes below.

sourcery_analytics.metrics.working_memory.method_working_memory(method: FunctionDef) int

Calculates the peak working memory within a method.

Parameters

method – a node for a function definition

Examples

>>> method_working_memory("def add(a, b): return a + b")
2
class sourcery_analytics.metrics.working_memory.WorkingMemoryVisitor(_condition_penalty: int = 0, _scoped_variables: Optional[Set[str]] = None)

Bases: Visitor[int]

Visitor to calculate the working memory of a node.

Working memory is contextual. Alone, its value is the number of variables, including attributes and function calls, within the node. Within conditionals, this value is incremented by the number of variables used in the conditional. If variables are assigned before the node, these also increment the working memory.

enter(node: NodeNG)

Updates visitor context then yields.

touch(node: NodeNG) int

Returns a “fact” about a node.

sourcery_analytics.metrics.working_memory.get_names(node: NodeNG) Set[str]

Returns the set of variable names in the node.

sourcery_analytics.metrics.working_memory.get_name(node: NodeNG) Optional[str]

The name of a single relevant node.