pycroscope.value

Value classes represent the value of an expression in a Python program. Values are the key data type used in pycroscope’s internals.

Values are instances of a subclass of Value. This module defines these subclasses and some related utilities.

dump_value() can be used to show inferred values during type checking. Examples:

from typing import Any
from pycroscope import dump_value

def function(x: int, y: list[int], z: Any):
    dump_value(1)  # Literal[1]
    dump_value(x)  # int
    dump_value(y)  # list[int]
    dump_value(z)  # Any
class pycroscope.value.TypeVarMap(*, typevars: Mapping[TypeVarParam, Value] | None = None, paramspecs: Mapping[ParamSpecParam, ActualArguments | ParamSpecParam | AnySig | FullSignature] | None = None, typevartuples: Mapping[TypeVarTupleParam, tuple[tuple[bool, Value], ...]] | None = None)

Immutable typed storage for type parameter substitutions.

class pycroscope.value.ClassOwner(module: str, qualname: str, identity: ast.AST | str)
class pycroscope.value.Value

Base class for all values.

can_assign(other: Value, ctx: CanAssignContext) Mapping[ExternalType(type_path='pycroscope.value.TypeParam'), Sequence[ExternalType(type_path='pycroscope.value.Bound')]] | CanAssignError

Whether other can be assigned to self.

If yes, return a (possibly empty) map with the TypeVar values dictated by the assignment. If not, return a CanAssignError explaining why the types are not compatible.

For example, calling a.can_assign(b, ctx) where a is Iterable[T] and b is List[int] will return {T: TypedValue(int)}.

This is the primary mechanism used for checking type compatibility.

can_overlap(other: Value, ctx: CanAssignContext, mode: OverlapMode) CanAssignError | None

Returns whether self and other can overlap.

Return None if they can overlap, otherwise a CanAssignError explaining why they cannot.

is_assignable(other: Value, ctx: CanAssignContext) bool

Similar to can_assign() but returns a bool for simplicity.

walk_values() Iterable[Value]

Iterator that yields all sub-values contained in this value.

substitute_typevars(typevars: TypeVarMap) Value

Substitute the typevars in the map to produce a new Value.

This is used to specialize a generic. For example, substituting {T: int} on List[T] will produce List[int].

is_type(typ: type) bool

Returns whether this value is an instance of the given type.

This method should be avoided. Use can_assign() instead for checking compatibility.

get_type() type | None

Returns the type of this value, or None if it is not known.

This method should be avoided.

get_fallback_value() Value | None

Returns a fallback value for this value, or None if it is not known.

Implement this on Value subclasses for which most processing can be done on a different type.

get_type_value(ctx: CanAssignContext) Value

Return the value produced by type(x) for values compatible with this one.

This powers class-based fallback logic such as dunder lookup. For exact values this should usually be an exact class object, while for imprecise values like TypedValue(T) it should generally preserve the possibility of subclasses.

simplify() Value

Simplify this Value to reduce excessive detail.

decompose() Iterable[Value] | None

Optionally, decompose this value into smaller values. The union of these values should be equivalent to this value.

class pycroscope.value.CanAssignContext(*args, **kwargs)

A context passed to the Value.can_assign() method.

Provides access to various functionality used for type checking.

make_type_object(typ: type | ClassOwner) TypeObject

Return a pycroscope.type_object.TypeObject for this concrete type.

get_call_result(callee: Value, args: Iterable[Value] = (), kwargs: Iterable[tuple[str | None, Value]] = (), node: AST | None = None) Value

Return the result of calling callee with the given arguments.

get_generic_bases(typ: type | ClassOwner, generic_args: Sequence[Value] = ()) Mapping[type | ClassOwner, TypeVarMap]

Return the base classes for typ with their generic arguments.

For example, calling ctx.get_generic_bases(dict, [TypedValue(int), TypedValue(str)]) may produce a map containing the following:

{
    dict: [TypedValue(int), TypedValue(str)],
    Mapping: [TypedValue(int), TypedValue(str)],
    Iterable: [TypedValue(int)],
    Sized: [],
}
get_type_parameters(typ: type | ClassOwner) Sequence[TypeVarParam | ParamSpecParam | TypeVarTupleParam]

Return declared generic parameters for typ, if available.

get_signature(obj: object) Signature | OverloadedSignature | None

Return a pycroscope.signature.Signature for this object.

Return None if the object is not callable.

signature_from_value(value: Value) None | Signature | BoundMethodSignature | OverloadedSignature

Return a pycroscope.signature.Signature for a Value.

Return None if the object is not callable.

resolve_name(node: Name, error_node: AST | None = None, suppress_errors: bool = False) tuple[Value, object]

Resolve a name for annotation evaluation.

get_relation_cache() MutableMapping[object, object] | None

Return storage for relation memoization, if supported by this context.

has_active_relation_assumptions() bool

Whether relation memoization should be disabled for this context.

record_any_used() None

Record that Any was used to secure a match.

record_protocol_implementation(protocol: type[object], implementing_class: type[object]) None

Record that implementing_class was shown assignable to protocol.

display_value(value: Value) str

Provide a pretty, user-readable display of this value.

class pycroscope.value.CanAssignError(message: str = '', children: list[~pycroscope.value.CanAssignError] = <factory>, error_code: ~pycroscope.error_code.Error | None = None)

A type checking error message with nested details.

This exists in order to produce more useful error messages when there is a mismatch between complex types.

display(depth: int = 2) str

Display all errors in a human-readable format.

pycroscope.value.assert_is_value(obj: object, value: Value, *, skip_annotated: bool = False) None

Used to test pycroscope’s value inference.

Takes two arguments: a Python object and a Value object. At runtime this does nothing, but pycroscope throws an error if the object is not inferred to be the same as the Value.

Example usage:

assert_is_value([], KnownValue([]))  # passes
assert_is_value([], TypedValue(list))  # shows an error

If skip_annotated is True, unwraps any AnnotatedValue in the input.

pycroscope.value.dump_value(value: T) T

Print out the Value representation of its argument.

Calling it will make pycroscope print out an internal representation of the argument’s inferred value. Use pycroscope.extensions.reveal_type() for a more user-friendly representation.

At runtime this returns the argument unchanged.

pycroscope.value.get_mro(typ: object, *, include_virtual: bool = False) tuple[type, ...]

Return the runtime MRO for a class-like object.

During static analysis, pycroscope replaces this with a value-level MRO that preserves generic specialization for synthetic and runtime classes.

pycroscope.value.get_attribute(obj: object, attr: str, /, *, on_class: bool = False, is_special_lookup: bool = False, receiver: object = None) object

Get an attribute of an object.

During static analysis, pycroscope replaces this with a value-level attribute getter that preserves generic specialization for synthetic and runtime classes. If receiver is passed, it is used as the value being accessed.

class pycroscope.value.AnySource(*values)

Sources of Any values.

default = 1

Any that has not been categorized.

explicit = 2

The user wrote ‘Any’ in an annotation.

error = 3

An error occurred.

unreachable = 4

Value that is inferred to be unreachable.

inference = 5

Insufficiently powerful type inference.

unannotated = 6

Unannotated code.

variable_name = 7

A VariableNameValue.

from_another = 8

An Any derived from another Any, for example as an attribute.

generic_argument = 9

Missing type argument to a generic class.

marker = 10

Marker object used internally.

incomplete_annotation = 11

A special form like ClassVar without a type argument.

multiple_overload_matches = 12

Multiple matching overloads.

ellipsis_callable = 13

Callable using an ellipsis.

unresolved_import = 14

An unresolved import.

class pycroscope.value.AnyValue(source: AnySource)

An unknown value, equivalent to typing.Any.

source: AnySource

The source of this value, such as a user-defined annotation or a previous error.

pycroscope.value.UNRESOLVED_VALUE = AnyValue(source=<AnySource.default: 1>)

The default instance of AnyValue.

In the future, this should be replaced with instances of AnyValue with a specific source.

class pycroscope.value.PartialValueOperation(*values)

Kinds of partially evaluated operations represented by PartialValue.

class pycroscope.value.PartialValue(operation: PartialValueOperation, root: Value, node: AST, members: tuple[Value, ...], runtime_value: Value)

Represents a partially evaluated expression.

class pycroscope.value.PartialCallValue(callee: Value, arguments: dict[str, Value], runtime_value: Value, node: AST)

Represents a partially evaluated call expression, where the function is known but the arguments are not.

class pycroscope.value.SuperValue(thisclass: Value, selfobj: Value | None = None)

Value representing a super() call.

super(typ, self) => SuperValue(thisclass=typ, selfobj=self)

class pycroscope.value.VoidValue

Dummy Value used as the inferred type of AST nodes that do not represent expressions.

This is useful so that we can infer a Value for every AST node, but notice if we unexpectedly use it like an actual value.

class pycroscope.value.FunctionOwner(module: str, qualname: str, identity: ast.AST | object)
class pycroscope.value.AliasOwner(module: str, qualname: str, identity: ast.AST | object)
class pycroscope.value.TypeVarParam(typevar: ExternalType(type_path='TypeVar') | ExternalType(type_path='typing_extensions.TypeVar'), owner: type | pycroscope.value.ClassOwner | pycroscope.value.FunctionOwner | pycroscope.value.AliasOwner | typing_extensions.Sentinel | None, bound: pycroscope.value.Value | None = None, default: pycroscope.value.Value | None = None, constraints: collections.abc.Sequence[pycroscope.value.Value] = (), variance: pycroscope.value.Variance = <Variance.INVARIANT: 3>, is_self: bool = False)
is_self: bool = False

Whether this TypeVar represents typing.Self.

class pycroscope.value.ParamSpecParam(param_spec: ExternalType(type_path='ParamSpec') | ExternalType(type_path='typing_extensions.ParamSpec'), owner: type | pycroscope.value.ClassOwner | pycroscope.value.FunctionOwner | pycroscope.value.AliasOwner | typing_extensions.Sentinel | None, default: pycroscope.value.Value | None = None, variance: pycroscope.value.Variance = <Variance.INVARIANT: 3>)
class pycroscope.value.TypeVarTupleParam(typevar_tuple: <class 'TypeVarTuple'>, owner: type | pycroscope.value.ClassOwner | pycroscope.value.FunctionOwner | pycroscope.value.AliasOwner | typing_extensions.Sentinel | None, default: pycroscope.value.Value | None = None, variance: pycroscope.value.Variance = <Variance.INVARIANT: 3>)
class pycroscope.value.TypeAlias(evaluator: collections.abc.Callable[[], pycroscope.value.Value], evaluate_type_params: collections.abc.Callable[[], collections.abc.Sequence['TypeParam']], evaluated_value: pycroscope.value.Value | None = None, type_params: collections.abc.Sequence['TypeParam'] | None = None, is_evaluating: bool = False)
evaluator: Callable[[], Value]

Callable that evaluates the value.

evaluate_type_params: Callable[[], Sequence[TypeVarParam | ParamSpecParam | TypeVarTupleParam]]

Callable that evaluates the type parameters.

evaluated_value: Value | None = None

Value that the type alias evaluates to.

type_params: Sequence[TypeVarParam | ParamSpecParam | TypeVarTupleParam] | None = None

Type parameters of the type alias.

is_evaluating: bool = False

Whether this type alias is currently being evaluated.

class pycroscope.value.TypeAliasValue(name: str, module: str, alias: TypeAlias, type_arguments: Sequence[Value] = (), type_arguments_are_packed: bool = False)

Value representing a type alias.

name: str

Name of the type alias.

module: str

Module where the type alias is defined.

class pycroscope.value.UninitializedValue

Value for variables that have not been initialized.

Usage of variables with this value should be an error.

pycroscope.value.UNINITIALIZED_VALUE = UninitializedValue()

The only instance of UninitializedValue.

class pycroscope.value.KnownValue(val: Any)

Equivalent to typing.Literal. Represents a specific value.

This is inferred for constants and for references to objects like modules, classes, and functions.

val: Any

The Python object that this KnownValue represents.

class pycroscope.value.KnownValueWithTypeVars(val: Any, typevars: TypeVarMap)

Subclass of KnownValue that records a TypeVar substitution.

typevars: TypeVarMap

TypeVars substituted on this value.

class pycroscope.value.SyntheticModuleValue(module_path: Sequence[str])

Represents a module that exists only in stub files.

class pycroscope.value.UnboundMethodValue(attr_name: str, composite: Composite, secondary_attr_name: str | None = None, typevars: TypeVarMap | None = None, owner: object | None = None)

Value that represents a method on an underlying Value.

Despite the name this really represents a method bound to a value. For example, given s: str, s.strip will be inferred as UnboundMethodValue("strip", Composite(TypedValue(str), "s")).

attr_name: str

Name of the method.

composite: Composite

Value the method is bound to.

secondary_attr_name: str | None = None

Used when an attribute is accessed on an existing UnboundMethodValue.

This is mostly useful in conjunction with asynq, where we might use object.method.asynq. In that case, we would infer an UnboundMethodValue with secondary_attr_name set to "asynq".

typevars: TypeVarMap | None = None

Extra TypeVars applied to this method.

owner: object | None = None

Owner that originally supplied the method, when known.

get_method() Any | None

Return the runtime callable for this UnboundMethodValue, or None if it cannot be found.

class pycroscope.value.TypedValue(typ: type | ClassOwner, literal_only: bool = False)

Value for which we know the type. This is equivalent to simple type annotations: an annotation of int will yield TypedValue(int) during type inference.

typ: type | ClassOwner

The underlying runtime type or synthetic class key.

literal_only: bool = False

True if this is LiteralString (PEP 675).

class pycroscope.value.NewTypeValue(name: str, value: Value, newtype: Any)

A wrapper around an underlying type.

Corresponds to typing.NewType.

This is a subclass of TypedValue. Currently only NewTypes over simple, non-generic types are supported.

name: str

Name of the NewType.

value: Value

The underlying value of the NewType.

newtype: Any

Underlying NewType object.

class pycroscope.value.GenericValue(typ: type | ClassOwner, args: Iterable[Value], *, weak: bool = False)

Subclass of TypedValue that can represent generics.

For example, List[int] is represented as GenericValue(list, [TypedValue(int)]).

args: tuple[Value, ...]

The generic arguments to the type.

weak: bool

Whether assignability should relax invariant generic arguments on the RHS.

class pycroscope.value.SequenceValue(typ: type | ClassOwner, members: Sequence[tuple[bool, Value]])

A TypedValue subclass representing a sequence of known type.

This is represented as a sequence, but each entry in the sequence may consist of multiple values. For example, the expression [int(self.foo)] may be typed as SequenceValue(list, [(False, TypedValue(int))]). The expression ["x", *some_str.split()] would be represented as SequenceValue(list, [(False, KnownValue("x")), (True, TypedValue(str))]).

This is only used for set, list, and tuple.

members: tuple[tuple[bool, Value], ...]

The elements of the sequence.

get_member_sequence() Sequence[Value] | None

Return the Value objects in this sequence. Return None if there are any unpacked values in the sequence.

make_known_value() Value

Turn this value into a KnownValue if possible.

class pycroscope.value.KVPair(key: Value, value: Value, is_many: bool = False, is_required: bool = True)

Represents a single entry in a DictIncompleteValue.

key: Value

Represents the key.

value: Value

Represents the value.

is_many: bool = False

Whether this key-value pair represents possibly multiple keys.

is_required: bool = True

Whether this key-value pair is definitely present.

class pycroscope.value.DictIncompleteValue(typ: type | ClassOwner, kv_pairs: Sequence[KVPair])

A TypedValue representing a dictionary of known size.

For example, the expression {'foo': int(self.bar)} may be typed as DictIncompleteValue(dict, [KVPair(KnownValue('foo'), TypedValue(int))]).

kv_pairs: tuple[KVPair, ...]

Sequence of KVPair objects representing the keys and values of the dict.

property items: Sequence[tuple[Value, Value]]

Sequence of pairs representing the keys and values of the dict.

get_value(key: Value, ctx: CanAssignContext) Value

Return the Value for a specific key.

class pycroscope.value.TypedDictEntry(typ: pycroscope.value.Value, required: bool = True, readonly: bool = False)
class pycroscope.value.TypedDictValue(items: dict[str, TypedDictEntry], extra_keys: Value | None = None, extra_keys_readonly: bool = False)

Equivalent to typing.TypedDict; a dictionary with a known set of string keys.

items: dict[str, TypedDictEntry]

The items of the TypedDict. Required items are represented as (True, value) and optional ones as (False, value).

extra_keys: Value | None = None

The type of unknown keys, if any.

extra_keys_readonly: bool = False

Whether the extra keys are readonly.

class pycroscope.value.SyntheticClassObjectValue(name: str, class_type: TypedValue | TypedDictValue, class_key: type | ClassOwner | None = None)

Represents a singleton class object that exists but has no runtime object.

class pycroscope.value.AsyncTaskIncompleteValue(typ: type | ClassOwner, value: Value)

A GenericValue representing an async task.

This should probably just be replaced with GenericValue.

value: Value

The value returned by the task on completion.

class pycroscope.value.CallableValue(signature: ~pycroscope.signature.Signature | ~pycroscope.signature.OverloadedSignature, fallback: type | ~pycroscope.value.ClassOwner = <class 'collections.abc.Callable'>)

Equivalent to the Callable type.

This is a thin wrapper around pycroscope.signature.Signature.

get_asynq_value() Value

Return the CallableValue for the .asynq attribute of an AsynqCallable.

class pycroscope.value.SubclassValue(typ: TypedValue | TypeVarValue)

Equivalent of Type[].

The typ attribute can be either a TypedValue or a TypeVarValue. The former is equivalent to Type[int] and represents the int class or a subclass. The latter is equivalent to Type[T] where T is a type variable. The third legal argument to Type[] is Any, but Type[Any] is represented as TypedValue(type).

typ: TypedValue | TypeVarValue

The underlying type.

classmethod make(origin: Value) Value

Construct the internal equivalent of type[origin].

This should only be called with values that are valid as the argument to type[...]: a type expression, Any, a TypeVar, or a union of those. If inference substitutes a runtime class object or literal value here, preserve the class case and degrade other invalid inputs instead of crashing.

class pycroscope.value.IntersectionValue(vals: tuple[Value, ...])

Represents the intersection of multiple values.

class pycroscope.value.OverlappingValue(type: Value)

Represents Overlapping[T].

class pycroscope.value.MultiValuedValue(raw_vals: dataclasses.InitVar[collections.abc.Iterable[pycroscope.value.Value]])

Equivalent of typing.Union. Represents the union of multiple values.

vals: tuple[Value, ...]

The underlying values of the union.

pycroscope.value.NO_RETURN_VALUE = MultiValuedValue(vals=())

The empty union, equivalent to typing.Never.

class pycroscope.value.ReferencingValue(scope: Any, name: str)

Value that is a reference to another value (used to implement globals).

class pycroscope.value.Bound
class pycroscope.value.LowerBound(type_param: TypeVarParam | ParamSpecParam | TypeVarTupleParam, value: Value)

LowerBound(T, V) means V must be assignable to the value of T.

class pycroscope.value.UpperBound(type_param: TypeVarParam | ParamSpecParam | TypeVarTupleParam, value: Value)

UpperBound(T, V) means the value of T must be assignable to V.

class pycroscope.value.OrBound(bounds: Sequence[Sequence[Bound]])

At least one of the specified bounds must be true.

class pycroscope.value.IsOneOf(type_param: pycroscope.value.TypeVarParam | pycroscope.value.ParamSpecParam | pycroscope.value.TypeVarTupleParam, constraints: collections.abc.Sequence[pycroscope.value.Value])
class pycroscope.value.TypeVarValue(typevar_param: TypeVarParam)

Value representing a typing.TypeVar.

class pycroscope.value.InferenceVarValue(typevar_param: TypeVarParam)

A fresh inference variable created from a declared TypeVar.

class pycroscope.value.TypeVarTupleValue(typevar_tuple_param: pycroscope.value.TypeVarTupleParam)
class pycroscope.value.TypeVarTupleBindingValue(binding: tuple[tuple[bool, 'Value'], ...])
class pycroscope.value.ParamSpecArgsValue(param_spec: ExternalType(type_path='ParamSpec') | ExternalType(type_path='typing_extensions.ParamSpec'))
class pycroscope.value.ParamSpecKwargsValue(param_spec: ExternalType(type_path='ParamSpec') | ExternalType(type_path='typing_extensions.ParamSpec'))
class pycroscope.value.Extension

An extra piece of information about a type that can be stored in an AnnotatedValue.

class pycroscope.value.SelfOwnerExtension(class_key: type | pycroscope.value.ClassOwner)
class pycroscope.value.CustomCheckExtension(custom_check: pycroscope.extensions.CustomCheck)
class pycroscope.value.ParameterTypeGuardExtension(varname: str, guarded_type: Value)

An Extension used in a function return type. Used to indicate that the parameter named varname is of type guarded_type.

Corresponds to pycroscope.extensions.ParameterTypeGuard.

class pycroscope.value.NoReturnGuardExtension(varname: str, guarded_type: Value)

An Extension used in a function return type. Used to indicate that unless the parameter named varname is of type guarded_type, the function does not return.

Corresponds to pycroscope.extensions.NoReturnGuard.

class pycroscope.value.TypeGuardExtension(guarded_type: Value)

An Extension used in a function return type. Used to indicate that the first function argument is of type guarded_type.

Corresponds to pycroscope.extensions.TypeGuard, or typing.TypeGuard.

class pycroscope.value.TypeIsExtension(guarded_type: Value)

An Extension used in a function return type. Used to indicate that the first function argument may be narrowed to type guarded_type.

Corresponds to typing_extensions.TypeIs (see PEP 742).

class pycroscope.value.TypeFormValue(inner_type: Value)

Represents a typing.TypeForm value.

class pycroscope.value.SyntheticTypeFormValue(inner_type: Value, runtime_type: Value, node: AST | None)

Represents an object that can be used in annotations, but for which we do not have a runtime object.

class pycroscope.value.AddPredicateExtension(varname: str, predicate: Predicate)

An Extension used in a function return type. Used to indicate that the function argument named varname should receive the predicate predicate.

class pycroscope.value.ConstraintExtension(constraint: AbstractConstraint)

Encapsulates a Constraint. If the value is evaluated and is truthy, the constraint must be True.

class pycroscope.value.NoReturnConstraintExtension(constraint: AbstractConstraint)

Encapsulates a Constraint. If the value is evaluated and completes, the constraint must be True.

class pycroscope.value.AlwaysPresentExtension

Extension that indicates that an iterable value is nonempty.

Currently cannot be used from user code.

class pycroscope.value.AssertErrorExtension

Used for the implementation of pycroscope.extensions.assert_error().

class pycroscope.value.SkipDeprecatedExtension

Indicates that use of this value should not trigger deprecation errors.

class pycroscope.value.DeprecatedExtension(deprecation_message: str)

Indicates that use of this value should trigger a deprecation error.

class pycroscope.value.SysPlatformExtension

Used for sys.platform.

class pycroscope.value.SysVersionInfoExtension

Used for sys.version_info.

class pycroscope.value.DefiniteValueExtension(value: bool)

Used if a comparison has a definite value that should be used to skip type checking.

class pycroscope.value.DataclassTransformInfo(eq_default: bool = True, frozen_default: bool = False, kw_only_default: bool = False, order_default: bool = False, field_specifiers: tuple[pycroscope.value.Value, ...] = ())
class pycroscope.value.DataclassInfo(init: bool, eq: bool, frozen: bool | None, unsafe_hash: bool, match_args: bool, order: bool, slots: bool, kw_only_default: bool, field_specifiers: tuple[pycroscope.value.Value, ...])
class pycroscope.value.DataclassFieldInfo(has_default: bool = False, init: bool = True, kw_only: bool = False, alias: str | None = None, converter_input_type: pycroscope.value.Value | None = None)
class pycroscope.value.PropertyInfo(*, fget: 'ClassSymbol | None', fset: 'ClassSymbol | None' = None, fdel: 'ClassSymbol | None' = None)
class pycroscope.value.DataclassTransformExtension(info: pycroscope.value.DataclassTransformInfo)
class pycroscope.value.DataclassTransformDecoratorExtension(info: pycroscope.value.DataclassTransformInfo)
class pycroscope.value.AnnotatedValue(value: Value, metadata: Sequence[Extension])

Value representing a PEP 593 Annotated object.

Pycroscope uses Annotated types to represent types with some extra information added to them in the form of Extension objects.

value: Value

The underlying value.

metadata: tuple[Extension, ...]

The extensions associated with this value.

get_metadata_of_type(typ: type[T]) Generator[T, None, None]

Return any metadata of the given type.

get_custom_check_of_type(typ: type[T]) Generator[T, None, None]

Return any CustomChecks of the given type in the metadata.

has_metadata_of_type(typ: type[Extension]) bool

Return whether there is metadata of the given type.

class pycroscope.value.VariableNameValue(varnames: Iterable[str])

Value that is stored in a variable associated with a particular kind of value.

For example, any variable named uid will get resolved into a VariableNameValue of type uid, and if it gets passed into a function that takes an argument called aid, the call will be rejected.

This was created for a legacy codebase without type annotations. If possible, prefer using NewTypes or other more explicit types.

There should only be a limited set of VariableNameValue objects, created through the pycroscope configuration.

classmethod from_varname(varname: str, varname_map: dict[str, VariableNameValue]) VariableNameValue | None

Returns the VariableNameValue corresponding to a variable name.

If there is no VariableNameValue that corresponds to the variable name, returns None.

class pycroscope.value.Predicate

Represents a predicate on a value, such as “has an attribute named ‘x’ of type int”.

has_relation(other: AnyValue | KnownValue | SyntheticClassObjectValue | SyntheticModuleValue | UnboundMethodValue | TypedValue | SubclassValue | TypeFormValue | PredicateValue | MultiValuedValue | IntersectionValue | OverlappingValue | TypeAliasValue | NewTypeValue | TypeVarValue | TypeVarTupleBindingValue | TypeVarTupleValue | ParamSpecArgsValue | ParamSpecKwargsValue | AnnotatedValue | PartialValue | PartialCallValue | SyntheticTypeFormValue | SuperValue, relation: Relation, ctx: CanAssignContext) bool

Whether this predicate has the given relation to another GradualType.

For example, whether other is a subtype of this predicate, meaning that all values included in the type are guaranteed to satisfy the predicate.

intersect_with(other: AnyValue | KnownValue | SyntheticClassObjectValue | SyntheticModuleValue | UnboundMethodValue | TypedValue | SubclassValue | TypeFormValue | PredicateValue | MultiValuedValue | IntersectionValue | OverlappingValue | TypeAliasValue | NewTypeValue | TypeVarValue | TypeVarTupleBindingValue | TypeVarTupleValue | ParamSpecArgsValue | ParamSpecKwargsValue | AnnotatedValue | PartialValue | PartialCallValue | SyntheticTypeFormValue | SuperValue, ctx: CanAssignContext) Value | None

Return a Value representing the intersection of this predicate with another GradualType, or None if the intersection is irreducible.

class pycroscope.value.PredicateValue(predicate: Predicate)

Represents a type-level predicate constraint.

exception pycroscope.value.NotAGradualType

Raised when a value is not a gradual type.

pycroscope.value.flatten_values(val: Value, *, unwrap_annotated: bool = False) Iterable[Value]

Flatten a MultiValuedValue into its constituent values.

We don’t need to do this recursively because the MultiValuedValue constructor applies this to its arguments.

if unwrap_annotated is true, produces the underlying values for AnnotatedValue objects.

pycroscope.value.unite_values(*values: Value) Value

Unite multiple values into a single Value.

This collapses equal values and returns a MultiValuedValue if multiple remain.

pycroscope.value.concrete_values_from_iterable(value: Value, ctx: CanAssignContext) CanAssignError | Value | Sequence[Value]

Return the exact values that can be extracted from an iterable.

Three possible return types:

  • CanAssignError if the argument is not iterable

  • A sequence of Value if we know the exact types in the iterable

  • A single Value if we just know that the iterable contains this value, but not the precise number of them.

Examples:

  • int -> CanAssignError

  • tuple[int, str] -> (int, str)

  • tuple[int, ...] -> int

pycroscope.value.kv_pairs_from_mapping(value_val: Value, ctx: CanAssignContext) Sequence[KVPair] | CanAssignError

Return the KVPair objects that can be extracted from this value, or a CanAssignError on error.

pycroscope.value.unpack_values(value: Value, ctx: CanAssignContext, target_length: int, post_starred_length: int | None = None) Sequence[Value] | CanAssignError

Implement iterable unpacking.

If post_starred_length is None, return a list of target_length values, or CanAssignError if value is not an iterable of the expected length. If post_starred_length is not None, return a list of target_length + 1 + post_starred_length values. This implements unpacking like a, b, *c, d = ....

pycroscope.value.is_iterable(value: Value, ctx: CanAssignContext) CanAssignError | Value

Check whether a value is iterable.

pycroscope.value.is_async_iterable(value: Value, ctx: CanAssignContext) CanAssignError | Value

Check whether a value is an async iterable.

pycroscope.value.replace_known_sequence_value(value: Value, ctx: CanAssignContext | None = None) AnyValue | KnownValue | SyntheticClassObjectValue | SyntheticModuleValue | UnboundMethodValue | TypedValue | SubclassValue | TypeFormValue | PredicateValue | MultiValuedValue | IntersectionValue

Simplify a Value in a way that is easier to handle for most typechecking use cases.

Does the following:

  • Replace AnnotatedValue with its inner type

  • Replace TypeVarValue with its fallback type

  • Replace KnownValues representing list, tuples, sets, or dicts with SequenceValue or DictIncompleteValue.

class pycroscope.value.ClassSymbol(*, annotation: pycroscope.value.Value | None = None, initializer: pycroscope.value.Value | None = None, qualifiers: frozenset[pycroscope.value.Qualifier] = frozenset(), function_decorators: frozenset[pycroscope.value.FunctionDecorator] = frozenset(), deprecation_message: str | None = None, is_instance_only: bool = False, is_method: bool = False, property_info: pycroscope.value.PropertyInfo | None = None, dataclass_field: pycroscope.value.DataclassFieldInfo | None = None)
class pycroscope.value.AnnotationExpr(ctx: 'pycroscope.annotations.Context', _value: pycroscope.value.Value | None, qualifiers: collections.abc.Sequence[tuple[pycroscope.value.Qualifier, ast.AST | None]] = <factory>, metadata: collections.abc.Sequence[pycroscope.value.Extension] = <factory>)