Changelog¶
Version 0.4.0 (May 2, 2026)¶
This release aims to strengthen robustness and quality, fixing many issues found in real-world code.
Add precise type inference for the result of
operator.getitem.Add a disabled-by-default
private_importerror code that flags imports and module attribute reads of single-underscore module members; pycroscope’s self check now enforces it.Recognize
warnings.deprecatedas a deprecation decorator in static fallback analysis, fixing missed deprecated diagnostics with newertyping_extensionsbackports.Fix false positive
unsafe_comparisonerrors when comparing a value narrowed by a length predicate against its original type.Preserve precise dictionary entries for
dict.fromkeys(), so known literal keys with a shared value can satisfy broaderdict[...]return annotations.Fix false positive
undefined_attributeerrors for@staticmethodmethods accessed through dataclass instances.Fix overload-only callable protocol methods so protocol compatibility checks use the declared overload set instead of the runtime overload placeholder.
Fix callable signature compatibility for syntactic
*args: Any, **kwargs: Anytails andParamSpec[...], so callable protocols interoperate with fixed signatures more consistently.Drop restrictions against redefined and function-local
typestatements.Support
typing_extensions.Sentineland (on Python 3.15+)builtins.sentinel, as specified by PEP 661.Clean up treatment of attributes to be more consistent and reliable. The
TreatClassAttributesAsAnyconfiguration is no longer supported.Fix bug where the constructors of two classes with the same name were mixed up.
Respect class-level runtime constructor signatures for some metaclass-driven and extension-backed classes, so keyword-only constructors like
repoguess.Params(...)no longer fall back to a bogusobject.__init__call shape.Make the command-line runner inject
typing.reveal_typeintobuiltinsbefore importing user modules, with a compatible fallback on older Python versions, so top-level runtime use ofreveal_type()no longer fails during CLI analysis.Weaken inferred constructor-return generics, so fresh values like
Box(1)and nesteddefaultdict(...)calls can satisfy broader annotated generic targets without forcing explicit specialization.Avoid internal errors for some constructor-style generic patterns like
type[T] | T, and stop showing a misleadingNone.module prefix in messages for generated callables.Make
type()results more consistent for imprecise values likestr,type[T], andsuper(), so pycroscope preserves subclass-aware class objects where appropriate and stops relying on implicit fallback behavior for internal type values.Simplify
type()lookups through narrowed intersections, sohasattr()-guarded class-object calls preserve the real constructor signature instead of picking up confusing fallback overloads likeobject.__init__.Fix assignability involving weak list literals in nested invariant containers, so values like
defaultdict(lambda: ([], []))can satisfy annotated tuple-valueddictentries instead of failing on the inner empty-list literals.Improve nested tuple mismatch diagnostics so assignments involving tuple-valued generics now report which tuple element failed instead of the vague message
tuple is not assignable to tuple.Add an opt-in
--find-unused-call-patternscheck, plusenforce_no_unused_call_patterns, to report parameters whose accepted call shapes are only partially exercised, including always-omitted defaults, one-sided boolean flags, and unused union members.Fix bare generic-class annotations so user-defined generics like
Capybaranow reportmissing_generic_parameters, and partially specialized forms likeCapybara[int]reportinvalid_specialization.Fix
hasattr()-driven narrowing bookkeeping so synthetic attributes no longer show up as fake unused members, and looped identity checks likevalue.param_spec is ps_args.param_specno longer poison nearby temporary-variable reads.Fix
hasattr()-based intersection lookup so class-object attributes likecls.__name__remain available after narrowing through unrelatedHasAttr[...]predicates.Fix class-object narrowing for unconstrained generic values, so combined checks like
isinstance(x, type) and issubclass(x, Base)now preserve the refinedtype[Base]information inside the resulting intersection instead of getting stuck atAny & type.Fix local attribute tracking for descriptor-backed optional attributes, so guarded writes like
if self.field is None: return; self.field = valuekeepself.fieldnarrowed within the current method instead of widening later reads back to the optional type.Fix fallback-mode
TypeVarTuplecallable inference so conformance-style checks likeProcess(target=..., args=...)now match fixed-arity callables more consistently.Make transformed instance attributes keep their declared types on writes, so bad assignments like
self.name = maybe_noneare reported and no longer widen laterself.namereads across a method or class.Fix false positive
incompatible_argumenterrors for numericsum()calls, so ordinary iterables likelist[int], generator expressions, anddict.values()type-check cleanly again.Add an opt-in
unreachablecheck that reports dead code after guaranteed termination and in impossible control-flow paths such as always-false branches and short-circuited boolean operands.Support PEP 800
@disjoint_baseclasses in intersection-based narrowing, so incompatibleTypeIs[...]checks on different disjoint bases now narrow toNever.Improve class-symbol decorator metadata so final, abstractmethod, and deprecation checks now reuse stored symbol information more consistently, including deprecated class/static methods and property accessors.
Fix cache-order-dependent protocol lookup for importable runtime types, so string-backed types like
contextlib.AbstractContextManager[T]no longer need a prior runtime lookup before context-manager protocol checks and self-checks succeed.Fix runtime method binding for Cython-backed descriptor methods, so chained calls like
self.method.asynq()no longer produce false positive call-arity errors or depend on fallback lookup.Improve
TypeVarinference for overloaded constructor callables, so patterns likemodel_field(converter=dict, default=())no longer fail by committing to the wrongdictoverload too early.Fix
Self-aware descriptor lookup so instance access keepsSelfthrough classmethod helper chains likeself.getter().get_one(), and class-level descriptor comparisons likeModel.parent == selfcan return custom query objects instead of collapsing tobool.Fix
__init_subclass__class-attribute initialization so projects can declare a class-level attribute contract on a base class and initialize it viacls.attr = ...without spurious instance-attribute errors.Make class-object attribute lookup prefer real runtime members before synthetic overlays, so descriptor-backed class attributes keep working even when method bodies assign through
self.attror transformed instance access is enabled.Fix runtime generic descriptor specialization so instances like
Field[int]()andField[Other | None]()keep their concrete payload types during attribute lookup instead of falling back to unspecialized~T.Fix
Self-typed iterator and query methods during fallback analysis, so classmethod patterns likefor i, obj in enumerate(cls.select()): ...andquery = cls.select()preserveSelfinstead of misbinding nested receiver types.Fix a method-binding regression in fallback analysis so inherited instance methods are bound exactly once, which removes false positive call-arity errors in projects that use transformed class attributes.
Fix a
Selfregression for generic receiver methods, so calls likeQuery[Self].filter() -> Query[Self]andGetter[Self].get_one() -> Self | Noneno longer get widened to nested receiver types during fallback analysis.Fix a user-visible regression in large project analysis so pycroscope no longer prints stray internal
__getitem__debug lines, and avoids internal errors when stub lookup touches runtime objects whose__getattr__methods can raise project-specific exceptions.Split overloaded annotation diagnostics into narrower ones: pycroscope now uses
invalid_self_usage,invalid_paramspec_usage, andinvalid_qualifierfor those specific mistakes, keeps other bad annotation forms underinvalid_annotation, uses declaration-specific codes likeinvalid_typeddict/invalid_namedtuple/invalid_overload/invalid_final/invalid_type_alias/invalid_protocol/invalid_type_parameter, reports duplicate type-alias statements asalready_declared, and reports callingAnnotatedaliases asnot_callable.Fix fallback-mode generic class-object assignability so synthetic classes now honor declared type-parameter defaults when compared against annotations like
type[Bar[str]].Fix several
Selfedge cases so generic classmethods preserve class arguments likeBox[int].make() -> Box[int],Self | Nonestays stable inside method bodies, andclsattribute writes usingSelfno longer produce false positives.Fix generic
NamedTuplesubclasses in import-failure analysis so inherited tuple fields and synthetic methods now keep specialized type arguments, which restores checks like tuple-style indexing and constructor argument validation for classes such asclass Child(Base[int]): ....Fix importable-mode runtime
NamedTupleconstructor inference so runtime classes preserve their concrete return types and tuple behavior without relying on fallback-analysis side effects.Fix
Selfhandling in class-body descriptor expressions so pycroscope now preserves owner-boundSelftypes in both importable and fallback analysis, instead of relying on syntax-specific workarounds.Fix several internal-error crashes and false positives when analyzing large projects: pycroscope now degrades ParamSpec input-signature placeholders safely in suggested-type generation, avoids treating ordinary container literals with unsupported elements as crashing implicit type aliases, snapshots
from module import *exports before lazy annotation work can mutate the source module dictionary, and no longer reports callable intersections asnot_callable.Fix two false positives around runtime analysis: subscripting ordinary values annotated with a type alias no longer looks like type-alias specialization, and unresolved
matchvalue patterns now fall back cleanly instead of reporting internal errors.Improve
TypeObjectattribute lookup for stub-backed members so runtime classes now merge direct stub symbols with runtime descriptors, preserving runtime descriptor shape while using stub type information for properties and other attributes.Fix class-object metaclass lookup so
TypeObject.get_attribute()now follows Python’s class-access rules, including bound metaclass members and metaclass properties overriding same-named class attributes.Improve
TypeObject.get_attribute()descriptor handling so instance-like access now resolves custom__get__descriptors more consistently, and class-object lookup correctly lets metaclass data descriptors win precedence over same-named class attributes.Route more synthetic attribute inference through
TypeObject.get_attribute(), preserving generic substitution, protocol matching, andSelf-aware synthetic classmethod behavior in import-failure and stub-only analysis.Fix dataclass definition diagnostics so invalid field ordering, conflicting
__slots__, andKW_ONLYdefaults now use a dedicatedinvalid_dataclasserror, and subclasses reject required fields that follow inherited defaulted fields.Fix
NamedTuplesubclass handling so overriding inherited fields is reported consistently in both module modes, andpycroscope.get_mro()preserves the specialized tuple base in import-failure analysis.Improve deprecated-member diagnostics for inherited properties and
__call__, so subclasses now inherit those deprecation errors consistently instead of sometimes losing them.Allow subclasses to add
__slots__entries without triggeringincompatible_override, while still rejecting writes to attributes that are not declared in inherited slots.Improve
matchfallthrough narrowing for irrefutable class and sequence patterns, so later cases and wildcard fallbacks now exclude values already guaranteed to match earlier branches.Fix attribute-assignment checks on unions and intersections so pycroscope now preserves special-case errors like
Final/ClassVarwrites and still validates declared attribute types across each possible receiver branch.Improve
super()modeling so pycroscope now trackssupercalls with a dedicated internal value, resolvessuper()attribute lookup more consistently, and accepts staticmethod access likesuper().label().Run Python 3.14 CI tests with coverage reporting, and keep a pinned set of fully covered modules at 100% coverage so regressions in files like
annotated_types.py,regex_check.py, andtype_evaluation.pyfail CI.Make the pytest suite fail on unexpected
DeprecationWarnings by default, so newly escaped deprecated APIs are caught unless a test intentionally filters them.Add
pycroscope.get_mro()and record value-level class MROs on type objects, so generic, tuple-subclass, namedtuple, and synthetic-class inheritance can now be inspected with preserved specialization.Improve type-parameter scoping for nested classes, class-body aliases, and PEP 695 generic declarations, so out-of-scope or legacy type parameters are rejected more consistently without changing existing variance checks.
Improve tuple-subclass modeling so
NamedTuplehandling relies more on recorded class information, readonly-field enforcement stays consistent, and exacttuple[...]subclasses preserve tuple-style behavior more accurately.Speed up self-checks and other constraint-heavy analysis by caching repeated composite-constraint inversion and application work in scope narrowing.
Fix
Self-annotated receiver attribute writes so attributes assigned throughself: Selforsetattr(self, ...)are recognized on instances instead of later being reported as undefined.Speed up repeated declared-symbol lookups for synthetic and runtime-backed classes, reducing checker overhead on large modules and self-check runs.
Improve
--find-unused-attributesso it now reports unused non-method attributes too, handles inheritance and overrides more accurately for polymorphic attribute access, treats concrete classes proven compatible with protocols as implementations of those protocols, skipsTypedDictfields and framework-generated members, and supports config hooks to ignore patterns likevisit_*methods on AST visitors and helper classes in test-only modules.Reduce
--find-unused-attributesfalse positives by ignoringdataclasses.InitVarpseudo-fields andgeneric_visit()methods on AST visitor classes.Add an
ignored_unused_attribute_pathsoption so individual unused-attribute findings can be suppressed by fully-qualified path, for examplepycroscope.analysis_lib.Sentinel.name.Restore the self-check’s unused-object enforcement so repo-wide self-checks once again fail on genuinely unused module-level objects.
Add an
enforce_no_unused_attributesoption so repo and self-check runs can fail on unused class attributes without needing--find-unused-attributes.Add PEP 767
ReadOnlyattribute support for classes and protocols, including assignment/deletion errors for readonly members, protocol matching for readonly attributes, andFinal-attribute deletion errors.Fix a crash when resolving inherited string annotations for instance attributes accessed through
clsin methods, so these attributes now infer their annotated types instead of raising an internal error.Improve
isinstance()narrowing for local class objects, includingNamedTupleclasses, so branches now narrow correctly even when the class object comes from pycroscope’s synthetic local-class representation.Improve
isinstance()narrowing for generic class objects, so checks likeif isinstance(x, typ):withtyp: type[T]now narrowxusing the type parameter instead of falling back to an imprecise type.Improve
TypeVarhandling by distinguishing declared type parameters from call-site inference variables, so pycroscope no longer solves rigidTypeVars during ordinary assignability checks and now preserves more accurate generic-call and recursive type-alias behavior.Fix context-manager inference for cases like
contextlib.nullcontext()and unions of different context manager implementations, sowithbindings and exit-type checks now keep the right types instead of falling back to imprecise results or spurious errors.Improve several inference edge cases:
iter(d.values())now produces anIteratorwith the right value type, tuple-valued attributes stay narrowed after truthiness andlen()checks, and bitwise operations onenum.Flag/re.RegexFlagpreserve the enum type.Restore concise generic-parameter names in invalid type-alias diagnostics, so errors mention forms like
~T: str,~P, andTsinstead of full internal parameter object reprs.Fix
Generic[...]andProtocol[...]base validation parity between importable and import-failure analysis, including PEP 695 class declarations likeclass C[T](Generic[T])that should be rejected consistently.Fix
@dataclass_transformparity between importable and import-failure analysis: pycroscope now reuses synthetic dataclass metadata for runtime-backed classes when checking attributes like__hash__and__match_args__, so hashability and class-pattern matching behave consistently in both modes.Reject more invalid
Selfusages: pycroscope now reports errors for module-levelSelf,Selfin type aliases or base-class expressions, and method signatures that useSelffrom staticmethods, metaclasses, or mismatched explicit receiver annotations.Fix constructor result specialization for
floatarguments and overloaded__init__methods, soassert_type()now agrees with pycroscope’s implicitfloat | intsemantics in cases likeBox(1.0)andBox[float](1).Fix
@dataclass_transformfield specifier checking for unimportable modules so converter-based defaults and constructor inputs work consistently for callables likedict.Fix generic scoping checks so pycroscope now rejects out-of-scope type parameters in local and class-body annotations, nested class definitions, class-body type aliases, and runtime type expressions like
list[T]()at module scope.Reclassify invalid inheritance diagnostics: pycroscope now reports
invalid_baseinstead ofinvalid_annotationfor class-base errors such as badGeneric[...]/Protocol[...]bases, inheriting from@finalclasses, and incompatible multipleTypedDictbases.Fix type-alias attribute handling in fallback mode:
Alias: TypeAlias = intnow uses runtimeintattributes, whiletype Alias = intcontinues to expose alias-object attributes like__value__.Improve
NamedTuplecompatibility for tuple-style indexing, unpacking, and item mutation checks.Enforce function-parameter annotations on later reassignments, so pycroscope now reports incompatible writes like reassigning
x: inttostror wideningLiteral[...]parameters with+=.Fix variadic type-alias specialization in static fallback mode: pycroscope now solves
TypeVarTuplearguments through aliases liketuple[*Ts, T1, T2]and preserves explicit empty-pack specializations such asArray[()]even when a module cannot be imported.Improve
Selfhandling in fallback mode for unimportable modules: pycroscope now resolves@propertygetters, inheritedSelf-annotated attributes, andcls/selfreceivers more accurately in advanced generic cases.Restore simple
assert_type()equivalence checking: pycroscope now compares the inferred type against the type form of the second argument directly, without special-case exact-type reconstruction for recent constructor and annotation patterns.Preserve empty
TypeVarTuplespecializations when converting runtime generic aliases back into types, so checks likeassert_type(x, tuple[str, Array[()]])continue to understandArray[()]instead of collapsing it to bareArray.Stop exposing enum instance-only descriptors like
.nameas class attributes on enum types; pycroscope now reports these as undefined on enum classes, matching Python runtime behavior.Fix several composite-type edge cases so pycroscope now preserves union/intersection handling when detecting missing async yields, deliteralizing enum attributes, and widening inferred
TypeVarTuplearguments.Treat
typing.TYPE_CHECKINGandtyping_extensions.TYPE_CHECKINGas statically true in control flow, soif TYPE_CHECKING:blocks are analyzed while runtime-only branches are skipped.Improve deprecated-diagnostic coverage in static fallback mode for unimportable modules: pycroscope now reports deprecations for
__call__, protocol methods, property getters/setters, and inplace-operation fallbacks (for examplex += y) more consistently.Improve generic default specialization behavior for both type aliases and classes: unsubscripted aliases/classes now use declared type-parameter defaults (rather than
Any), overspecialization is reported consistently, and static fallback mode now preserves these semantics after import-time runtime failures.Fix deprecated-overload inference when overload definitions are wrapped (for example by
typing_extensions.deprecated): pycroscope now follows__wrapped__for overload signatures while preserving deprecation diagnostics on the selected overload.Add a global
typeshed_pathoption to override the typeshed root pycroscope uses for typeshed-client resolution, accepting either a directory withVERSIONSor one withstdlib/VERSIONS, and now reporting a clear error if neither exists.Add a new
pycroscope.extensions.Overlapping[T]type primitive: assignments toOverlapping[T]now accept values whose types overlap withT(that is,T & Uis notNever).Fix
Selfreturn checking for methods and classmethods: pycroscope now rejects returning concrete base-class instances from-> Selfmethods (for examplereturn Shape()), which previously slipped through as valid.Improve PEP 695 scoping checks by rejecting type-parameter bounds/constraints that depend on other type parameters, and preserve module execution order in import-failure fallback mode so top-level uses before assignment now report
undefined_name.Improve variance and generic-call checking in static fallback mode for unimportable modules: legacy
TypeVar(..., infer_variance=True)now infers class variance from member usage, legacyGeneric[T]classes preserve their type parameters more reliably, and generic@dataclassconstructor calls retain explicit type arguments.Improve type-inference handling of
|type expressions in value position: pycroscope now preserves and resolves type-form unions (including metaclass types) without relying solely on runtime__or__/__ror__, fixingassert_type(...)checks likeconstructors_call_metaclass.py.Fix constructor-call checking with generic metaclass passthrough methods: when a metaclass
__call__is just*args/**kwargs -> T, pycroscope now falls back to class__new__/__init__signatures instead of incorrectly accepting missing constructor arguments.Fix
TypeVarTupletype-alias specialization for explicit empty and unpacked forms: aliases likeIntTuple[()]andTA9[*tuple[int, ...], str]now preserve variadic bindings instead of defaulting toAnyor nesting tuple arguments incorrectly.Improve generic base handling in static-fallback analysis: pycroscope now preserves
Generic[...]type-parameter order when imports fail, validatesGeneric[...]/Protocol[...]base arguments and coverage, rejects generic metaclass specialization, and preserves constrainedTypeVarcorrelations in binary operations likeAnyStrconcatenation.Improve generator annotation checking: pycroscope now reports missing returns based on a generator’s declared return component (
Generator[..., ReturnT]) and accepts protocol-based generator return annotations (for example protocols defining__next__/__anext__).Conformance CI runs now disable the
must_useerror code so typing-conformance comparisons ignore intentionally discarded generator-expression values (such asassert_type(...)checks).Improve
@dataclass_transformconverter support: synthesized constructor argument types and dataclass field assignment checks now use converter input types, anddefault_factorychecks now validate against converter inputs instead of converted field types.Fix
TypeVarTupleconcatenation in generic-class specialization so annotations likeArray[Batch, *Shape]now infer asArray[Batch, ...]rather than collapsing to a single tuple type argument.Improve callback-protocol compatibility for callable metadata members: pycroscope now treats function
__name__/__module__/__qualname__asstr, avoids false protocol override/assignment errors for these members, and reports unknown attribute writes on protocol-typed callables.Fix
TypeVarTupleunpack handling in generic class annotations: pycroscope now correctly type-checks patterns likeArray[Batch, *tuple[Any, ...], Channels]andArray[*tuple[Any, ...]]in both normal and static-fallback analysis.Fix protocol constructor-call handling for abstract class objects: pycroscope no longer reports spurious
Cannot instantiate protocol class ...errors when calling through values typed astype[Proto]that may refer to concrete implementers.Improve explicit-protocol checks in import-failure fallback mode: pycroscope now rejects abstract
super()protocol calls without defaults, enforces protocol-declared member assignment types, and correctly flags instantiation of explicit protocol implementers that still have abstract members.Improve explicit
TypeAliashandling: pycroscope now preserves generic alias metadata (includingParamSpec) forAlias: TypeAlias = ..., reports invalid alias specializations more consistently, and treats unsubscriptedCallable[P, T]aliases asCallable[..., T].Improve recursive type-alias checks: pycroscope now specializes recursive implicit generic aliases correctly, rejects circular
TypeAliasunions more consistently, and reports runtime calls to union alias values as invalid.Reduce runtime-import side effect leakage in module-scope inference for local class instances, improving
assert_type(...)stability for dataclassFinalfields even when later assignments mutate runtime objects.Fix override checking for class and dataclass attributes so pycroscope now reports
incompatible_overridewhenClassVarand instance variables override each other across inheritance.Fix generic type-erasure class attribute checks: pycroscope now rejects class-object reads/writes of instance-only annotated attributes (including specialized generic aliases like
Node[int].label), instead of allowing runtime import side effects to mask these errors.Improve
LiteralStringinference for f-strings: pycroscope now preservesLiteralStringfor f-strings whose formatted expressions are allLiteralString-compatible, and falls back tostrwhen any expression is notLiteralString.Improve
Valuedispatch handling in name-check helper paths so enum_ignore_parsing, dataclass default detection, type-parameter identity extraction, and runtime-literal index checks process unions/intersections consistently.Fix
@dataclass_transformmarker recognition to use inferred decorator values, so unrelated decorators nameddataclass_transformare no longer treated as PEP 681 markers. Also improve support for other dynamic variations on dataclass_transform and dataclass decorators.Improve
annotated_typeslength-check metadata handling for unions/intersections by normalizing through fallback values and computingMinLen/MaxLenbounds more consistently.Apply intersection-based narrowing for positive
isinstance(...),issubclass(...),TypeIs[...], andis_of_type(...)checks in more paths, aligning these checks with other intersection constraint handling.Improve recursive protocol matching with
@classmethodmembers: pycroscope now preserves classmethod parameter constraints andSelfspecialization in synthetic static-fallback analysis, fixing false protocol incompatibilities and downstreamAnyinference.Improve generic-base-class analysis in static fallback mode for unimportable modules: pycroscope now preserves generic base mappings and type-parameter ordering more accurately, reports duplicate/conflicting generic base type-variable declarations, and rejects
Generic/Generic[...]used as type annotations outside base-class lists.Improve PEP 695 generic declaration checks: pycroscope now rejects
Generic[...]/Protocol[...]specialization inclass C[T]bases, handles forward references in type-parameter bounds/constraints without spuriousundefined_nameerrors, and reports invalid type-parameter constraint tuples with fewer than two types.Preserve literal type arguments when inferring generic class-syntax
NamedTupleconstructor return types (for example,Box(1)now infersBox[Literal[1]]).Improve
TypeVarTuplehandling for generic classes in static-fallback analysis: pycroscope now preserves variadic argument lengths andNewTypemembers during inference, and correctly reports incompatible tuple lengths across repeated uses.Fix static-fallback generic-class specialization with
TypeVarTuplebases so annotations likeArray[Height, Width]no longer spuriously report wrong type-argument arity after an import-time runtime failure in the same module.Generalize repeated
TypeVarTupleinference so same-length element mismatches merge to per-position unions across call contexts (including*args: tuple[*Ts]and callable packs), while still rejecting mismatched tuple lengths.
Version 0.3.0 (March 1, 2026)¶
This release includes a large number of changes aimed at improving compliance with the Python typing spec. While many features are still missing or incomplete, there is now some degree of support of all major type system features.
Improve
TypeVarTuplesolving for repeated tuple-parameter uses (for exampledef f(*args: tuple[*Ts])): incompatible tuple shapes across arguments are now rejected, and same-length element mismatches are inferred as per-position unions.Remove additional name-based receiver checks in protocol and call-signature handling, so nonstandard receiver names no longer affect protocol-member binding or TypedDict-backed dict-method checks.
Reduce name-based method heuristics by checking receiver parameters structurally in more places, which improves consistency for methods that don’t use literal
self/clsnames.Improve generic protocol checking by honoring
Protocol[...]type-parameter order and rejecting protocol matches with unsatisfiable cross-member type-variable constraints.Improve method-receiver handling by using inferred receiver semantics instead of hard-coded
self/clsnames, so checks forFinalinstance attributes, protocol-member synthesis, enum_value_assignments, and receiver attribute writes now behave correctly with nonstandard receiver names.Improve protocol/class-object conformance for class-object assignments: pycroscope now enforces method/property/class-variable compatibility more accurately (including static-fallback analysis for unimportable modules).
Fix
@dataclass_transformmetadata tracking to live on inferred values instead of scope-name side tables, which avoids internal errors in cases likeParamSpecdeclarations andglobal/nonlocalreferences.Improve
ParamSpeccomponent checking and forwarding: pycroscope now rejects more invalidP.args/P.kwargsannotation and call forms, accepts validConcatenateforwarding patterns likefoo(1, *args, **kwargs), and no longer reportsgenerics_paramspec_componentsas a known conformance failure.Improve ParamSpec handling in static-fallback analysis for unimportable modules: generic classes like
Y(Generic[U, P])now preserve ParamSpec type parameters fromGeneric[...]bases, list-form specializations likeY[int, [int]]are interpreted correctly, and callable attributes likey.fspecialize to concrete signatures.Improve descriptor handling for dataclass-like classes (
@dataclassand@dataclass_transform): constructor parameters now use descriptor__set__value types for data descriptors, and class/instance attribute reads now follow descriptor__get__return types.Tighten ParamSpec specialization checks for generic classes: pycroscope now reports
invalid_annotationfor invalid mixed-generic forms likeC[int, int]when the second parameter is aParamSpec, while still accepting valid forms likeC[int, [int]],C[int, P],C[int, Concatenate[str, P]], andC[int, ...].Improve
Valuedispatch consistency in suggested-type and class-key inference helpers by normalizing through fallback values and handling unions/intersections more consistently.Improve
Valuedispatch robustness in name checking so enum assignment analysis, protocol-base detection, and type-parameter extraction handle unions/intersections consistently and avoid internal errors on non-gradual values.Improve intersection-type attribute checks so pycroscope now enforces slot restrictions, frozen-dataclass immutability, and NamedTuple field immutability for
Intersection[...]instance values.Improve class-object resolution for annotated and generic values in core name checking, reducing false negatives in protocol-instantiation, enum-base, and attribute-target checks.
Improve protocol/class-object compatibility checks by handling more class-value forms consistently (including
SubclassValuegeneric wrappers andtype-typed values).Improve
@contextmanager/@asynccontextmanagerinference: decorated callables now keep context-manager return types, andwith ... as xnow infers the yielded value type more precisely.Improve constraint narrowing consistency by routing
isinstance(...)andis ...checks through relation-based subtype logic, reducing edge-case mismatches across complex value kinds.Apply NamedTuple runtime-call suppression consistently by removing the special-case exemption for classes in
pycroscope.*modules.Update internal
@contextmanagerreturn annotations to useGenerator[...], improving compatibility with newer typing/typeshed behavior.Improve protocol compatibility in static fallback mode for unimportable modules: pycroscope now enforces ClassVar-vs-instance member distinctions, writable data-member/property rules (including setter requirements), and supports plain writable attributes for read-only protocol properties.
Fix tuple-literal equivalence checks so
Literal[("x",)]is treated as equivalent totuple[Literal["x"]]in subtype/equivalence relations.Improve dataclass constructor/pattern semantics in static fallback mode: pycroscope now honors class-level
init/match_argssettings for@dataclassand@dataclass_transform, and recognizesfactory=field specifier defaults when checking generated constructors anddefault_factoryreturn types.Improve dataclass conformance in static fallback mode for unimportable modules: pycroscope now validates default-before-non-default field ordering, checks
default_factoryreturn types against field annotations, preserves callable dataclass fields as values (not bound methods), exposes dataclass metadata (__dataclass_fields__), and resolves inherited dataclass constructors more accurately.Tighten
TypeVarTuplevalidation: pycroscope now reportsinvalid_annotationfor unpacking mistakes liketuple[Ts],*args: Ts,Generic[Ts], andGeneric[*Ts1, *Ts2], and no longer emits spuriousUnrecognized annotation typing.Unpack[...]errors for annotations likeArray[*Shape].Improve
TypeVardefault validation: pycroscope now reportsinvalid_annotationwhen defaults conflict with bounds or constraints, enforcesGeneric[...]default-order rules (including import-failure fallback mode), and treats unspecialized synthetic class objects as compatible with specializedtype[...]forms.Improve constructor checking when modules fail at import time: pycroscope now enforces explicit
__init__self-annotation compatibility for specialized generic class calls (for example rejectingClass4[str]()when__init__requiresClass4[int]), and avoids false positives from synthetic class-subscripting fallback on generic instances.Improve
TypeAliasType(...)handling: variadic alias specialization now supportsTypeVarTuple, runtimetype_paramsscope/literal-tuple and circular-definition checks are enforced, and recursive alias evaluation no longer triggers internal recursion errors.Fix variance checks in static fallback mode for unimportable modules by recovering generic type parameters from base annotations, which removes false
invalid_annotationerrors and restores expected nested-alias variance errors (for examplegenerics_variance.py).Fix a crash in type relation checks when comparing generic arguments that mix ParamSpec call-signature values with non-ParamSpec values; pycroscope now reports a regular type mismatch instead of
internal_error.Accept ParamSpec list specialization syntax in generic classes (for example
C[[int]]forclass C[**P]), matching the typing spec’s allowed form.Improve static fallback analysis for unimportable modules by pre-registering synthetic methods and persisting
self/clsattribute assignments, reducing falseundefined_attributeerrors in class methods.Tighten typing-construct arity validation in annotations (including
ClassVar/Final/Requiredqualifiers and runtimeCallable[...]parsing), so malformed argument lists are reported more consistently.Improve
@dataclass_transformfield specifier default handling: pycroscope now infers implicitinitvalues from field-specifier signatures (including overload defaults likeLiteral[False]), fixing constructor checks for cases likedataclasses_transform_field.py.Improve dataclass
slotschecking (including@dataclass_transformclasses): pycroscope now surfaces__slots__for slotted dataclasses, rejectsslots=Trueclasses that also define__slots__, and reports invalid assignments to attributes not declared in slots (including static fallback mode for unimportable modules).Fix callable protocol compatibility for
__call__signatures in import-failure fallback mode (including*args: Any, **kwargs: Anyellipsis-style tails andConcatenate[..., ...]interop), improving conformance forcallables_annotation.py.Improve generic alias constructor checking in static fallback mode: calls like
Node[int](...)now preserve explicit type arguments for inference and enforce constructor argument types.Improve protocol conformance by rejecting protocol instantiation and fixing generic/variance protocol subtyping checks, including static fallback handling for protocol generic bases when runtime import metadata is incomplete.
Improve static fallback analysis for unimportable modules by resolving synthetic class instance methods from synthetic bases in expression contexts, reducing false
undefined_attribute/inference_failurecascades for cases likeSelf-typed methods.Improve static fallback analysis for unimportable modules by making synthetic
@classmethodattributes callable and preservingSelfreturn specialization (for example inferringCirclefromCircle.from_config(...)).Improve
ClassVarconformance checks: pycroscope now rejectsClassVaroutside class-body attribute declarations (including type aliases), reports errors for assignments to class variables through instances, and adds a newclassvar_type_parameterserror code (disabled by default) for rejectingClassVartype parameters (TypeVar/ParamSpec); conformance CI now enables this stricter check.Improve static fallback analysis for unimportable modules by resolving synthetic class instance methods from synthetic bases in expression contexts, reducing false
undefined_attribute/inference_failurecascades for cases likeSelf-typed methods.Fix dataclass hashability inference (including
@dataclass_transformclasses): mutableeq=Trueclasses are now treated as unhashable unlessunsafe_hash=Trueor an explicit__hash__is provided, in both normal analysis and import-failure fallback mode.Improve dataclass
InitVarhandling:__post_init__signatures are now validated againstInitVarfields (including inherited fields), andInitVarmembers are now correctly rejected as instance attributes, fixing conformance fordataclasses_postinit.py.Align
@dataclass_transformmetaclass inheritance with the typing spec: classes that directly specify a transform-decorated metaclass are now treated as neither frozen nor non-frozen, which fixes conformance behavior fordataclasses_transform_meta.py.Replace internal starred-expression handling with
PartialValueUNPACKoperations, removing_StarredValueand making partial unpack evaluation consistent across annotations and runtime expression analysis.Enforce type-variable variance compatibility in class inheritance through generic aliases, so invalid bases like
Base[T_co]and aliased equivalents now reportinvalid_annotation.Tighten
Callable[...]annotation validation to match the typing spec: pycroscope now correctly rejects invalid forms likeCallable[int],Callable[int, int],Callable[int, int, int], andCallable[[...], T].Improve dataclass and
@dataclass_transformconstructor/comparison checking: synthetic dataclass constructors no longer inherit non-dataclass base__init__parameters, generic transform bases now propagate correctly (includingBase[T]forms), and</<=/>/>=comparisons now enforce dataclass ordering rules.Add initial PEP 681
@dataclass_transformsupport: classes transformed by marked decorators, base classes, or metaclasses now get dataclass-like constructor/frozen semantics in both normal analysis and static fallback mode when imports fail.Honor standard
# type: ignorecomments (including top-of-file file-level ignores), so pycroscope now suppresses errors in the same places users expect from typing-spec directives.Reduce false-positive
incompatible_overrideerrors for protocol-style method overrides by comparing callable signatures more consistently in override checks.Improve
ParamSpechandling by rejecting invalid annotation locations more consistently (including bareParamSpectype aliases,list[P], andCallable[..., P]return positions), and enforce assignment-target name matching forTypeVar,TypeVarTuple,ParamSpec,NewType, and functionalNamedTuple/TypedDictdeclarations.Improve
TypeVarTuplecallable checking by preserving unpacked tuple parameters in callable argument lists, improving inference for variadic*argspatterns, and keeping constructor-call checking precise for synthetic classes in static fallback analysis.Improve protocol runtime-check checks:
issubclass()now rejects@runtime_checkabledata protocols, andisinstance()/issubclass()now reportincompatible_argumentfor unsafe-overlap runtime-checkable protocol checks that could succeed at runtime despite incompatible member types.Improve synthetic constructor-to-callable inference: pycroscope now synthesizes more accurate callable signatures for overloaded
__init__/__new__, honors custom metaclass__call__, preserves localnamedtupleconstructor behavior, and handles dataclass constructor fallback (including class vars and import-failure subclasses) more accurately.Improve static fallback analysis for dataclasses with keyword-only fields:
KW_ONLYpseudo-fields no longer raiseinvalid_annotation, and kw-only constructor arguments are now checked correctly even when modules fail at import time.Allow
@overridemethods in subclasses ofAny-derived base classes (for exampleclass Parent(Any): ...) instead of incorrectly reportingoverride_does_not_override.Enforce PEP 695 generic-syntax compatibility rules for classes and generic functions/methods: pycroscope now reports
invalid_annotationwhen old-styleTypeVar/ParamSpec/TypeVarTupledeclarations are mixed into newclass C[T]ordef f[T](...)annotation contexts.Add protocol variance validation for both legacy
Protocol[T]and PEP 695 generic syntax: pycroscope now reportsinvalid_annotationwhen declared protocol type-variable variance does not match inferred usage (including unused protocol type variables, which default to covariant).Add a new
invalid_literalerror code (disabled by default) to flagLiteral[...]arguments that are outside the typing-spec allowed set, and enable this check in conformance CI runs.Tighten
type-statement alias semantics: type aliases are no longer accepted as class bases orisinstance/issubclassclassinfo arguments, alias metadata attributes like__value__/__type_params__are handled consistently,typestatements are rejected inside function scope, and pycroscope now reports alias redeclarations/invalid unguarded alias cycles plus bound/constraint violations when specializingTypeAliasTypealiases (including ParamSpec list-form arguments);isinstance/issubclassnow also reject TypedDicts, non-@runtime_checkableprotocols, and parameterized generics in classinfo arguments.Improve constructor-call checking through
type[T]: pycroscope now validates constructor arguments for both unbounded and boundedTypeVarclass objects, and rejects extra arguments for classes that use the default no-argument object constructor.Improve
typing.NewTypehandling in static fallback mode (when modules fail at import): pycroscope now preserves NewType constructor results, validates NewType base-type restrictions (for exampleAny, protocols,TypedDict, literals, and generic forms), and reportsNewTypeassignment-target name mismatches.Add frozen-dataclass enforcement in both normal and import-failure fallback analysis: assigning to frozen dataclass instance attributes is now rejected, and mixing frozen/non-frozen dataclass inheritance now reports errors.
Preserve generic type arguments more consistently: unsubscripted generic aliases now default their parameters to
Any, and constructor calls through generic aliases (for exampleListAlias[int]()) keep static type arguments instead of erasing them to bare runtime container types.Improve
TypeVarbound handling by accepting forward-reference string bounds that refer to names defined later in the file, and by reportinginvalid_annotationwhen a bound is parameterized by type variables (for examplebound=list[T]).Improve
Finalhandling for dataclasses by allowingClassVar[Final[T]]in dataclass bodies and by not requiring default-lessFinaldataclass fields to be explicitly assigned in__init__.Unify synthetic class handling by storing synthetic generic/protocol metadata on each synthetic class object, and fix nested local-class intersections so annotation-only members (for example
x: int) are recognized in attribute checks.Improve static fallback analysis for unimportable modules:
TypeVar(...)results are now preserved in annotations,type[A | B]unions are analyzed without runtime|,type[...]now enforces single-argument arity, andtyping.Typealias values now report undefined attributes correctly.Replace the internal
_SubscriptedValuewith a publicPartialValuetype that records partial expression evaluation details (including operation kind and runtime fallback value), improving extensibility for partially evaluated type expressions.Improve protocol checking in import-failure fallback mode by preserving synthetic protocol members and restoring protocol-merging checks (including invalid protocol bases and abstract-class instantiation diagnostics), which fixes conformance coverage for
protocols_merging.py.Infer variance for PEP 695 class type parameters from class member usage and generic base classes, improving assignment checks for covariant and contravariant generics.
Accept union arguments for constrained
TypeVarparameters when each union member matches at least one constraint, including calls likere.compile(pattern)wherepatternisstr | bytes.Generalize class-call signature inference to use Python-level metaclass
__call__methods (not just enum classes), improving call checking for custom metaclasses.Allow setting
output_formatinpyproject.tomlso users can choose concise or detailed error output from config files.Improve enum analysis in import-failure fallback mode by preserving enum-member semantics for synthetic classes, validating declared enum
_value_types, and avoiding falseunsafe_comparisonerrors for enum identity checks.Improve overload checks in import-failure fallback mode by preserving synthetic base-class relationships for override/final validation, fixing false
override_does_not_overridereports and missed final-method override errors.Fix internal errors in static fallback analysis for unimportable modules involving zero-argument
super()and property setters in synthetic classes.Improve qualifier checking by rejecting calls to
Annotatedaliases, enforcingFinalrules more consistently (including decorator semantics and class-member initialization), and preserving these checks when modules cannot be imported.Fix an internal error on bare
ParamSpecreturn annotations, and now report bareParamSpecannotations as invalid in direct return/parameter/variable contexts instead of crashing.Fix a crash in import-failure fallback mode when checking protocols that inherit generic bases (for example
Iterable[T]), by resolving inherited protocol members statically instead of treating them as missing.Annotate
matchpattern AST nodes in annotate mode, soannotate_code()and self-check no longer leaveMatch*nodes withoutinferred_value.Fix an internal error when checking equality comparisons between dataclass instances in modules that fail at import time.
Preserve
@overloadbehavior in static fallback mode when a module cannot be imported, including overload-aware inference for synthetic class dunder methods like__getitem__and consistency checks against overload implementations.Preserve generic base information for synthetic classes in static fallback mode, so subclasses like
class D(dict[str, int])are assignable todict[str, int].Improve tuple typing behavior by validating invalid
tuple[..., ...]/multi-unbounded-unpack forms, preservingtuple[T, ...]semantics when runtime imports fail, and improving tuple narrowing in sequence-patternmatchcases.Improve NamedTuple analysis in both normal and import-failure fallback modes: class-syntax NamedTuple definitions now enforce field/base-class rules, constructor/type inference is more precise (including generics), and tuple indexing/unpacking/type-compat checks now use NamedTuple field types instead of falling back to
Any.Tighten attribute-store checks: assigning to or deleting
NamedTuplefields through attribute syntax now reports errors, and assignments to existing annotated attributes now reportincompatible_assignmentwhen types do not match.Replace internal
**kwargsTypedDict special-casing with dictionary-entry modeling, so TypedDict dict/Mapping assignability rules stay consistent while dict-method calls on TypedDict values still type-check correctly.Tighten TypedDict conformance by enforcing class-syntax and inheritance checks in importable modules (not only fallback analysis), and by ignoring uninhabitable
NotRequired[Never]keys inTypedDict.update().Respect declared
TypeVarvariance in generic assignability and subtyping checks, so covariant, contravariant, and invariant type parameters are enforced correctly.Fix callable subtyping checks for
**kwargsso callable protocols compare keyword value types correctly even with invariant generic relation checking.Tighten
**kwargs: Unpack[...]callable handling: pycroscope now requires a concreteTypedDictinsideUnpackfor**kwargs, rejects overlapping named parameters, and disallows assigning plain keyword-only callables to protocols that require unpackedTypedDictkwargs.Remove the unused
requirements.txtcontributor setup file; local development setup now usesuv syncanduv run.Improve inference for function-local
collections.namedtuple(...)definitions by modeling the generated class as a synthetic local class object with a stable qualified name.Tighten TypedDict operation checking: declared TypedDict variables now keep TypedDict semantics after reassignment, dict literals with unknown or non-literal keys are rejected when assigning to TypedDicts, and
TypedDict.clear()/TypedDict.popitem()now report errors for non-closed TypedDicts or when required/readonly keys are possible.Improve fallback analysis for unimportable modules so synthetically analyzed
TypedDictdeclarations keepextra_items/closedsemantics (including functionalTypedDict(...)forms), which greatly improves conformance coverage fortypeddicts_extra_items.py.Fix functional
TypedDict(...)field parsing forRequired[]andReadOnly[], and restore assignment compatibility betweenProtocol[P]callables andCallable[P, ...]aliases in conformance checks.Preserve static typing-helper inference for module-scope assignments in importable modules when import-time runtime values would otherwise erase that typing information.
Avoid runtime deprecation warnings during analysis by using non-deprecated coroutine detection and suppressing speculative-call deprecation warnings, which speeds up large runs like self-check.
Add a Python 3.12 CI workflow for typing conformance that runs unit tests for the conformance tooling and then fails if pycroscope’s conformance outcomes diverge from the known-failing case list.
Speed up repeated analysis runs (including the test suite) by reusing typeshed resolvers across checker instances when stub search paths are the same.
Speed up checker setup by loading regex-related default argspecs only when regex functions are analyzed.
Speed up large analysis runs by memoizing repeated type-relation checks in assignability/subtyping logic.
Make implicit
TypeFormchecks side-effect-free so relation memoization stays safe and suppresses redundant work.Suppress annotation errors while evaluating runtime forward references, so diagnostics are not misattributed to the current module.
Improve string forward-reference diagnostics by reporting errors on the original annotation lines rather than line 1, avoiding duplicate reports from the collect/check passes, and supporting multiline triple-quoted string annotations (parsed as implicitly parenthesized expressions).
Validate that overloaded implementations are compatible with their
@overloadsignatures (including async/decorator-transformed signatures), and report overload/implementation mismatches with the newinconsistent_overloaderror code.Fix callable protocol subtyping when
__call__is overloaded, so pycroscope uses the declared overload signatures instead of a generic*args, **kwargsfallback.Fix
assert_type(..., Callable[..., Any])equivalence checks.Fix
type[None]annotations sotype(None)is accepted andNonevalues are rejected in type-checked calls.Fix handling of historical positional-only parameters (
__x) in source code: keyword calls to these parameters now error correctly, and invalid definitions likedef f(x, __y): ...are now reported under a dedicatedinvalid_positional_onlyerror code.Allow constructor calls to TypedDict classes that are analyzed syntactically (for example when runtime class objects are unavailable), so
MyTypedDict(...)is type-checked normally in those cases.Report an error for
isinstance(obj, SomeTypedDict)to match TypedDict runtime semantics.Report an error when
TypedDictis used as aTypeVarbound.Report
invalid_annotationfor nested duplicate qualifiers (for exampleFinal[Final[int]]) and for invalidTypedDictitem qualifier combinations, including conflictingRequired[]/NotRequired[], nestedReadOnly[], and unsupported qualifiers likeClassVar[].Improve TypedDict checking when runtime class objects are unavailable (for example after import-time failures or for function-local class definitions) by falling back to syntactic TypedDict analysis, so
ReadOnly/Required/NotRequiredannotations and inheritance conflicts are still reported.Validate functional
TypedDict(...)declarations more strictly by reporting errors for non-literal field mappings, non-string field names, and mismatched type names in assignments.Preserve functional
TypedDict(...)type information even when runtime keyword-form construction is unavailable (for example on Python 3.13+), avoiding spurious call errors and follow-on annotation failures.Report
invalid_basefor synthetic TypedDict classes that mixTypedDictwith non-TypedDictbase classes or bareGeneric(onlyGeneric[...]is allowed).Improve handling of class objects that come from stubs or unimportable modules by tracking them as singleton class values, which improves compatibility checks for TypedDict class objects and type-expression evaluation.
Create synthetic class objects for non-TypedDict classes when runtime class objects are unavailable (for example after import-time failures), so class self-references continue to resolve and nominal class values are preserved.
Treat synthetic class objects as class objects in assignability checks, so APIs expecting
type(for exampleTypedValue(...)) accept synthetic classes.Preserve dynamic
Any-base behavior for synthetic classes while keeping declared methods precise, so checks likeClassA(Any).method1()retain annotated return types and unknown members still behave asAny.Fix
Selfinference for classmethods on class objects loaded from stubs (including unimportable modules), so calls likeX.from_config()now infer instance results correctly.Treat
withblocks as non-suppressing when__exit__/__aexit__return types include non-boolmembers likeNone | bool, which improves narrowing after the block.Report
unused_variableandunused_assignmentfor annotated assignments likex: int = valuewhen the assigned value is never read.Narrow tuple types after
len()checks when bounds imply a more specific shape, including exact-length refinements and lower-bound refinements for tuples with fixed and variadic parts, which simplifiesreveal_type()output.Extend
len()-based narrowing to use intersection predicates, which also improves narrowing for non-tuple cases such as literal strings and impossibleTypedDictlength branches.Fix false-positive errors in some
len()-narrowed branches involvingAny & Predicate[...]intersections (includingassert_type(..., Any)and some sequence indexing operations).Fix a crash when accessing attributes on
len()predicate constraints by treatingPredicateValueattributes like attributes onobject.Fix dunder method handling on intersection types so operations like indexing
list[...] & Predicate[...]values no longer produce spurious errors andAny[error]inference.Keep unexpected keyword argument names in call errors in source order, so repeated runs produce stable output.
Make protocol member lists in type incompatibility messages deterministic by using definition order when available and sorted order otherwise.
Fix an internal error on Python 3.12+ when parsing PEP 695 generics that include
**P(ParamSpec) type parameters.Fix crash if accessing a module’s
__annotations__raises an error.Implement PEP 747
TypeFormsupport, including implicit and explicitTypeFormevaluation, assignability checks, and conformance tests.Require
typing_extensions>=4.13.0.Drop support for Python 3.9 and add official support for Python 3.14.
Narrow attribute and subscript expressions in nested scopes based on narrowing checks in the outer scope.
Apply the
class_attribute_transformersplugin also for values that have a__get__method.Fix internal error in certain cases involving custom
__getattr__methods that raise an error.Reduce the set of dependencies (
ast_decompileris no longer used;tomliis only used before Python 3.11;codemodis an extra).Package a
py.typedfile for pycroscope itself.Ignore presence of
__slots__in protocols defined in stubs.Change implementation of implicit int/float and float/complex promotion in accordance with https://github.com/python/typing/pull/1748. Now, annotations of
floatimplicitly meanfloat | int.Fix assignability for certain combinations of unions,
Annotated, andNewType.Reduce more uninhabited intersections to
NeverKeep checking files when module import fails, and report
import_failedon the line that triggered the import-time error (so it can be ignored with# static analysis: ignore[import_failed]).Fix crashes on unsupported syntax in string forward references by reporting regular
invalid_annotationerrors instead.Fix a crash in callable assignability involving
Concatenate[...,]signatures represented asAnySig.Fix crash when checking certain
TypeAliasTypespecializations that include unhashable runtime arguments (e.g. ParamSpec argument lists).Fix a crash when checking overloaded
@staticmethoddefinitions that involveParamSpec-based callable signatures.Preserve overload-based return inference for
@staticmethodand@classmethoddefinitions.Avoid errors in generic-base extraction when runtime annotations include
TypeVarTupleparameters, includingtyping_extensions.TypeVarTupleon Python 3.10.Suppress
missing_returnfor known abstract stub bodies (protocol methods and@abstractmethodmethods) when the body is just...orpass(including optional docstrings), while still reportingmissing_returnfor@abstractmethodmethods with nontrivial bodies.Fix a crash when checking classes that inherit from
typing.Any.Narrow variables correctly when calling
TypeGuardorTypeIsfunctions defined as@staticmethod, including calls through either instances or classes.Fix a crash when handling
typing.Annotatedon Python 3.14, where stubs expose it as an annotated assignment (Annotated: _SpecialForm).
Version 0.2.0 (June 26, 2025)¶
Fix crash on class definition keyword args when the
no_implicit_anyerror is enabled.Fix incorrect treatment of
ParamSpecin certain contexts.Add basic support for intersection types with
pycroscope.extensions.Intersection.Fix crash on checking the boolability of certain complex types.
Support subtyping between more kinds of heterogeneous tuples.
Treat
booland enum classes as equivalent to the union of all their members.Add support for unpacked tuple types using native unpack syntax (e.g.,
tuple[int, *tuple[int, ...]]; the alternative syntax withUnpackwas already supported).assert_type()now checks for type equivalence, not equality of the internal representation of the type.Improve parsing of annotation expressions as distinct from type expressions. Fixes crash on certain combinations of type qualifiers.
Improve support for recursive type aliases
Correctly handle type aliases and other types with fallbacks in more places
Fix edge case in
TypeIstype narrowing with tuple typesRewrite the implementation of assignability to be more in line with the typing specification
Fix handling of
ClassVarannotations in stubsFix operations on
ParamSpecArgsandParamSpecKwargsvaluesFix incorrect assignability relation between
TypedDicttypes anddict[Any, Any]; the spec requires that these be considered incompatibleFix bug where certain binary operations were incorrectly inferred as Any
Fix bug with generic self types on overloaded methods in stubs
Add support for NewTypes over any type, instead of just simple types
Add support for a concise output format (
--output-format concise)Fix treatment of aliases created through the
typestatement in union assignability and in iterationMake
asynqandqcoreoptional dependenciesFix use of aliases created through the
typestatement in boolean conditions
Version 0.1.0 (May 3, 2025)¶
First release under the pycroscope name. See the pyanalyze docs for the previous changelog.
Changes relative to pyanalyze 0.13.1:
Update PEP 728 support to the latest version, using the
extra_items=class argument instead of an__extra_items__key in the dict.Add support for Python 3.13
Drop support for Python 3.8
Flag invalid regexes in arguments to functions like
re.search.