Repository navigation
chore(deps): update dependency astroid to v4 - #362
Open
renovate[bot] wants to merge 1 commit into
Open
renovate[bot] wants to merge 1 commit into
renovate[bot] wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
🟢 Approval recommended
The updated dependency exists and is compatible with the documentation build’s Python 3.12 environment.
0 open findings
What changed in this PR
Updates Astroid for Sphinx AutoAPI documentation generation.
Changes:
- Bumps Astroid from 3.3.11 to 4.3.4.
| File | Description |
|---|---|
docs/requirements.txt |
Updates the pinned Astroid documentation dependency. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
renovate
Bot
force-pushed
the
renovate/astroid-4.x
branch
from
October 26, 2026 23:12
f11947a to
4edf0be
Compare
renovate
Bot
force-pushed
the
renovate/astroid-4.x
branch
from
December 4, 2026 03:01
4edf0be to
afb7c1a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Note
This PR body was truncated due to platform limits.
This PR contains the following updates:
==3.3.11→==4.4.0Release Notes
pylint-dev/astroid (astroid)
v4.4.0Compare Source
What's new in astroid 4.4.0?
Release date: 2026-11-30
Breaking Changes
Support for Python 3.10 was dropped, along with the
PY311_PLUSconstant and thetyping-extensionsruntime dependency. Python 3.11 is now the minimum version.Closes #3375
New Features
t-strings (TemplateStr) are now inferred: a t-string is inferred asan instance of
string.templatelib.Templateand an interpolation field as aninstance of
string.templatelib.Interpolation. Their members arereconstructed from the actual template contents, so
Template.strings/values/interpolationsandInterpolation.value/expression/conversion/format_specinfer to the same values as at runtime,including inside a called function, and adding two t-strings infers to the
concatenated template. A
TemplateorInterpolationbuilt by calling theclass directly is still a plain instance with uninferable members. The
standard library defines those classes via
type(t"..."), which is notstatically inferable, so a brain plugin rebuilds the real classes from the live
objects.
as_stringnow also escapes literal braces and quotes in theconstant parts of a t-string so the rendered code round-trips.
Closes #2789
Inference now narrows values through conditions joined by
andandor.A variable tested by several constraints at once, as in
if isinstance(apple, int) and apple != 3, keeps only the values satisfyingevery operand, and the
orand negated forms are handled too. Inference staysconservative when an operand cannot be inferred or does not constrain the
variable.
Closes #2977
When
--prefer-stubsis enabled in Pylint,.pyistub files are now loadedand used during inference, and compiled extensions with an adjacent stub use
the stub instead of runtime introspection. Stub functions whose bodies contain
only
...,pass, or a docstring infer the return type from the annotation.Closes #3078
Inference now narrows values through the preceding operands of
andandor. Inx is not None and x, the lastxno longer infersNone.In
x is None or x, the lastxis only evaluated whenx is Noneisfalse, so that condition is applied inverted. Constraints from several
preceding operands, including nested boolean operations, are combined.
Refs #3101
Refs pylint-dev/pylint#1498
Add a brain for
numpy.dtypes, whose DType classes (StringDType,Float64DType, ...) NumPy attaches at import time, so they can now be inferred. Each class gets its own constructor rather thannumpy.dtype's(obj, align, copy), so pylint no longer reportsno-memberon them norno-value-for-parameter/unexpected-keyword-argon calls such asStringDType(na_object=None).Closes #3289
Refs pylint-dev/pylint#9956
Inference now narrows values through conditions negated with
not.not isinstance(x, int),not (x is None)andnot (isinstance(x, int) and x == 3)used to constrain nothing; they nowbehave like the inverted condition in
ifstatements, conditionalexpressions, comprehensions and boolean operations.
Refs #3368
Refs pylint-dev/pylint#8331
Inference now narrows values after guard statements. After
if x is None: return,xno longer infersNone, andassert isinstance(x, int)keeps only theintvalues ofxfor thecode after it. An
ifis a guard when its body ends withreturn,raise,continueorbreak. An assignment between the guard and the useis not narrowed, and neither is a function, lambda or class defined after the
guard.
Refs #3369
Closes pylint-dev/pylint#9809
Inference now narrows values after an
ifwhose body assigns the name. Afterif x is None: x = [],xno longer infers theNoneit had before theif. This works for names and attributes, such asself.xorcls.x, withany condition that inference already narrows on.
Refs #3387
Closes pylint-dev/pylint#5085
Closes pylint-dev/pylint#4121
Closes pylint-dev/pylint#3045
Closes pylint-dev/pylint#2855
Inference now narrows values with
callable(x)conditions. Afterif callable(x):,xno longer infers values that cannot be called, andafter
if not callable(x):it no longer infers values that can.Refs #3391
Refs pylint-dev/pylint#1493
Bug Fixes
Keep applying subsequent transforms when a transform returns
None, preservingthe current node instead of stopping the transform chain.
Closes #809
Infer list augmented concatenation with a tuple as a list, rather than Uninferable.
Closes #1865
dataclass_transform()now always returns the transformedClassDefnode sosubsequent
Enuminference still populates__members__on@dataclass(init=False)and custom-
__init__enum classes.Refs #2317
Add support for NumPy 2.x, fixing false positives when analyzing
code that uses NumPy 2.
Closes #2710
dataclasses.replace(obj, ...)is now inferred as an instance ofobj's ownclass instead of being inferred through the stdlib body of
replace(). That bodyresolves
obj.__class__through the metaclass chain, which fails when a base is asubscripted generic such as
Base[T]: the call becameUninferablewith theold-style
Generic[T]syntax, and resolved to the wrong class with PEP 695class Base[T]syntax. The concrete caller type is now propagated correctly,including through
Self-annotated method chains.Refs #3061
Fix inference of callable instances stored as attributes, including attributes
with a same-named member on the callable. Infer the result of calling the
instance instead of looking up the attribute name on it again.
Refs #3077
modutils.get_source_fileno longer returns a compiled module as if it weresource. Bytecode (
.pyc/.pyo) and binary extension modules(
.so/.pyd/.dll) now fall through to the regular stub/source lookup,so a
.pyistub sitting next to a compiled module is found again instead ofthe compiled file being handed back and then parsed as source.
Closes #3087
Require a C extension to be located in the standard library before its
standard library name allows it to be imported. A name such as
colorsyswas trusted on its own, so an extension of that name sitting next to the
analysed sources was imported, and its module initialisation run, without
being on
extension-pkg-allow-list. Extensions shipped with theinterpreter are unaffected.
Refs #3193
Do not infer a functional
Enumwhose class name is not a string. Such adefinition is invalid at runtime and could expose a non-string class name to
consumers.
Refs #3212
Refs pylint-dev/pylint#11229
modutils.module_in_pathno longer reports a module as living under adirectory when its path only shares a leading name with that directory, such as
a module in
proj_extramatching the pathproj. It now uses the sameseparator-aware containment check as
_get_relative_base_path.Refs #3223
as_string()no longer renders an f-string whose delimiter reappearsunescaped in its body. Such an f-string terminated early and either failed to
parse or reparsed to a different expression, which matters because
brain_dataclassesandbrain_namedtuple_enumreparseas_string()output.
Refs #3235
as_string()no longer raisesValueErroron an integer constant toolarge to
repr()(pastsys.get_int_max_str_digits()); such integers arerendered as hex literals instead. This crashed the dataclass transform when a
field was shadowed by a property returning e.g.
10 ** 5000.Refs #3236
The fallback
__new__of the object model, used when the real one cannot be found(
instance.__new__,super().__new__(cls)under an uninferable ancestor, or the__new__of a C type outsidebuiltins), now has the signature(cls, *args, **kwargs)instead of(self, cls). Since__new__takes theclass explicitly, the old signature reported the class argument as missing and any
other argument as unexpected.
Closes #3237
Closes pylint-dev/pylint#8325
Refs pylint-dev/pylint#10670
Fix a crash when inferring a
super()call inside a function that is decoratedwith
@classmethodbut is not defined inside a class.Refs #3240
Closes pylint-dev/pylint#8755
AsStringVisitorno longer lets a docstring break out of the triple-quotedliteral it is rendered into. A docstring value containing
""", ending in aquote, or holding a NUL byte previously closed the literal early or, through the
DOC_NEWLINEsentinel, injected extra lines intoas_string()output, whichthe dataclass and namedtuple brains reparse. Such values now fall back to
reprso the output round-trips.Refs #3249
Infer a
str/bytesold-style%interpolation without crashing when a%cconversion receives an out-of-range code point, such as"%c" % 0x110000or
b"%c" % 256. The evaluation now catchesOverflowErrorand yieldsUninferable, matching the other invalid interpolations.Refs #3254
Infer an
enummember whose integer value is past the int-to-str conversionlimit, such as
A = 0xff...(a large hex literal the tokenizer accepts).Refs #3256
Fix an
AttributeErrorcrash when inferring atyping.NamedTuplesubclassor an
enum.Enumwhose body contains an assignment target that is not a plainname, such as the annotation
a.b: stror the chained assignmentx = a.b = 1.Such targets do not name a field or member and are now skipped.
Closes #3257
brain_gionly importsgifor a barerequire_version(...)call when thename actually resolves to gi, no longer for an unrelated function of that name.
Refs #3277
The numpy brain no longer imports
numpyto find out its version but readsfrom the installed package metadata instead.
Refs #3308
Fix an
IndexErrorcrash when inferring a functionalenum.Enumcallwhose member list contains an empty tuple, such as
enum.Enum("E", [()]).Such an invalid member now degrades to
Uninferableinstead of raising.Refs #3332
Fix
TypeErrorinFunctionDef.infer_call_resultfor a function namedwith_metaclasswhen the caller is a function, such as the decorator'sparent while inferring
FunctionDef.type.Closes #3336
A class attribute is now inferred with the values assigned to it through the
class in the module that defines it, as in
cls.attr = valuein a classmethod or
Klass.attr = value, along with the value set in the class body.Only the latter used to be inferred, so pylint reported
unsubscriptable-object,unsupported-membership-testand similar errorson lazily initialized class attributes such as
cache = None. A valueassigned to an attribute of a parent class also no longer leaks into a
subclass that assigns the same attribute in the same scope.
Refs #3351
Closes pylint-dev/pylint#9250
Closes pylint-dev/pylint#9809
Closes pylint-dev/pylint#10082
Refs pylint-dev/pylint#3045
Fix an
AssertionErrorwhen inferring a namedtuple, or a class derived fromtyping.NamedTuple, ifcollections.namedtupleitself cannot be inferred.The namedtuple is now built as if
rename=False.Refs #3352
Fix
TypeErrorinClassDef.ancestors()whentyping.Tupleortyping.Callableis first inferred with an exhausted inference context.The synthesized class was built with an uninferable base and reused for
every later inference.
Closes #3366
Fix a crash when inferring an attribute that resolves to a method proxying
something other than a function.
Refs #3370
Refs pylint-dev/pylint#10345
Add a
nametoSlicenodes, giving"slice"like other inferred builtinvalues (
Const,List,Dict...) give the name of their type. Asliceobject used as a class base, metaclass, exception or
super()argument no longercrashes code that reads the name of an inferred value.
Unknownnodes now have apytype()too, like theirnameandqname(),so every value inference returns can be asked for its name, qualified name and type.
Refs #3373
Refs pylint-dev/pylint#11609
Infer the name bound by a
typestatement as atyping.TypeAliasTypeinstance instead of the aliased value, so
__value__and the other aliasattributes are found on it.
Refs #3374
Refs pylint-dev/pylint#10091
Fix an uncaught
TypeErrorwhen inferring a starred name nested in afortarget, such asfor a, (b, *c) in ..., over an element theinference cannot see into.
Closes #3378
Do not cache inference results that were truncated by the inference budget.
Caching them made inference results depend on the order in which modules were analysed.
Closes #3383
Closes #3464
Closes pylint-dev/pylint#11582
Refs pylint-dev/pylint#9549
Thanks to @budhitha for the astroid-only reproducer behind #3464.
Prevent a
TypeErrorininfer_typing_aliaswhen_alias()is called witha non-integer constant second argument.
Closes #3389
Source files are now closed when reading fails during module building.
Closes #3404
FunctionDef.getattr()andLambda.getattr()no longer add the specialattribute to
instance_attrswhen an attribute such as__name__is bothassigned on the function and a special attribute. The stored list used to grow by
one on every lookup.
ClassDef.repr_tree(ast_state=True)no longer raisesAttributeError.Refs #3411
Fix a crash when inferring
len()on an instance whose__len__is notcallable, such as a module. The call is now uninferable instead.
Refs #3426
Fix
AttributeErrorwhen callingqname()on a generator expression or alist, set or dict comprehension. They are now named
<genexpr>,<listcomp>,<setcomp>and<dictcomp>, like<lambda>, which also shows in their repr.Refs #3427
Stop inferring a
__get__attribute on generators, which are notdescriptors. Accessing it is now reported as
no-member, like theAttributeErrorat runtime, instead of crashing attribute inference.Refs #3428
Fix
AttributeErrorwhen inferring the call result of a subclass oftypewithout a caller.Refs #3429
ClassDef.has_dynamic_getattr()now always returns a bool. It returnedUninferablewhen the__getattr__of a metaclass could not be inferred.Refs #3430
modpath_from_file()no longer raisesImportErrorfor a module inside a namespacepackage that also exists in
site-packages: the namespace package is now looked up fromthe directory the module is resolved from.
Refs #3445
Refs pylint-dev/pylint#10278
Fixed
isinstance()andissubclass()inference constraint when the classinfo is aPEP 604 union, e.g.
isinstance(x, int | str).Refs #3453
Apply the
!s,!rand!aconversions when inferring f-strings, sof'{"a"!r}'is inferred as"'a'"instead of'a'.Refs #3461
Infer names bound by an import in an enum class body as enum members, like
assigned names, instead of as the plain imported object.
Refs #3466
Closes pylint-dev/pylint#10951
Do not treat values wrapped in
enum.nonmember()as members of the enum.They were listed in
__members__, so pylint reportedinvalid-enum-extensionwhen such a class was extended, for example on any Django 6
models.Choicessubclass.
Closes #3467
Refs pylint-dev/pylint#6887
Fix a hang when inferring a class whose
__bool__reads attributes that arenarrowed by a truthiness guard (
if self.left:). The truthiness constraintnow passes the inference context to
bool_value(), so the recursion guardapplies.
Refs #3473
Closes pylint-dev/pylint#11807
Only treat a function as a property because of its decorator's name, like
@lazyor@reify, when the function is defined in a class body. Afunction decorated this way elsewhere stays a function, so it is no longer
inferred as a property object that is not callable.
Refs #3475
Closes pylint-dev/pylint#3586
typing.NamedTupleis now inferred as atuplesubclass with_asdict,_replace,_fields,_makeand_field_defaults, as typesheddeclares it.
selfin a method of atyping.NamedTuplesubclass finds thatAPI and the tuple methods such as
countandindexthrough it, so pylintno longer reports
no-member,unsubscriptable-objectornot-an-iterableonselfthere.Refs #3476
Closes pylint-dev/pylint#7891
The
ctypesbrain now gives thevalueargument ofc_int,c_char,c_doubleand the other simple types the same default as at runtime(
0,0.0,b"\x00","\x00"orFalse).apple = c_int()nolonger makes pylint emit
no-value-for-parameteron interpreters where_ctypesis a built-in module, such as the uv and python-build-standalonebuilds.
Refs #3482
Fix a false positive for
functools.partialobjects stored as class attributes: before Python 3.14, accessing one through an instance does not bindself, and astroid no longer infers a bound method for it.Refs #3491
Closes pylint-dev/pylint#2271
Other Changes
A
RecursionErrorraised while parsing a file is now enriched with a notenaming the file that could not be parsed, and advising to raise the recursion
limit (from pylint:
--init-hook='import sys; sys.setrecursionlimit(2000)').Closes #2974
Internal Changes
Remove
register_builtin_transformfromastroid.brain.brain_builtin_inference.It was only meant for astroid's own builtin brain, which now declares its inference
functions in a static dispatch table.
Refs #1115
The changelog is now assembled by
towncrierfrom news fragments indoc/whatsnew/fragments/, like in pylint. Add a<issue>.<type>fragmentthere instead of editing a changelog file.
Closes #3209
Performance Improvements
Collapse the 19 builtin inference transforms into a single dispatcher
transform on
nodes.Call. The transform visitor previously ran 19predicates per Call node, each repeating the same
isinstancechecks;the dispatcher does them once and routes by name via a dict.
Refs #1115
v4.3.4Compare Source
What's new in astroid 4.3.4?
Release date: 2026-10-08
Bug Fixes
Fix a
RecursionErrorwhen building a module from a live object that holds acontainer containing itself.
Closes #2974
Closes pylint-dev/pylint#10459
Arguments.default_value()no longer raisesIndexErrorwhen a keyword-onlyargument repeats the name of
*argsor**kwargs, as indef f(x, *y, y).Closes #3259
Fix an infinite loop when introspecting a live class that exposes itself, or a
sibling class, as one of its own attributes.
Closes #3284
Fix a
TypeErrorcrash when inferringrandom.sample()on a sequence whoseelements are inferred as
Instance.Closes #3310
Catch
ValueErrorduring comparison inference (such as invalid byte values in bytes membership checks) and returnUninferableinstead of raising an uncaught exception.Closes #3333
A function whose body is only
...is now inferred to returnUninferableinstead of
None, the same as a function whose body is onlypass. Thisis the astroid part of the fix for a false positive
not-callablein pylintwhen calling a
...property stub, such as thesqlalchemy.funchelpers.Refs #3347
Refs pylint-dev/pylint#8138
v4.3.3Compare Source
What's new in astroid 4.3.3?
Release date: 2026-09-30
Bug Fixes
Preserve the length of inferred list and tuple concatenations when an element
has multiple possible values. An ambiguous or uninferable element is now
represented as unknown instead of being expanded into multiple sequence items.
Refs #3221
Closes pylint-dev/pylint#2621
Fix
TypeErrorinClassDef.getitemwhen__class_getitem__is uninferable.Closes #3312
Fix
AssertionErrorinNodeNG.root()when inferringClass.__bases__, which previously returned a parentlessTuple.Closes pylint-dev/pylint#11491
v4.3.2Compare Source
What's new in astroid 4.3.2?
Release date: 2026-09-25
Bug Fixes
Fix a crash when a
namedtupleorEnumtype name or field namecontains
str.formatmarkup, as innamedtuple("{0}", "abc"). The nameis interpolated into an error message that astroid then reformats, so
building the message raised
IndexError. Inference now falls back to itsdefault.
Closes #3199
Infer a functional
TypeVarorNewTypewhose name is not an identifierwithout splicing that name into the synthesized class source. A crafted value
such as
TypeVar("T(Base): #")no longer breaks out of the identifierposition to inject bases or a body; the name is assigned to the class verbatim.
Refs #3217
Raise
InferenceErrorinstead of crashing withIndexErrorwhen a classuses
six.with_metaclass()with no positional metaclass argument, both whilebuilding the module and when the call is inferred.
Refs #3248
ClassDef.slots()no longer crashes on a class that declares a PEP 695type parameter literally named
__slots__(e.g.class C[__slots__]:).The type parameter's
TypeVarnode was mistaken for the class's actual__slots__value;slots()now returnsNonefor such classesinstead of raising
AttributeError.Refs #3258
Fix a crash when inferring an f-string or
str.format()call whosecformatspec gets an out-of-range code point, such as
f"{-1:c}". These now infer toUninferable, like the%ccase fixed in #3254.Closes #3301
The
argsattribute of an exception instance is now inferred as atupleinstance of unknown contents instead of a known empty tuple, so unpacking
exc.argsno longer looks unbalanced.Closes pylint-dev/pylint#11312
v4.3.1Compare Source
What's New in astroid 4.3.1?
Release date: 2026-08-17
Fix inference of the attributes of a
namedtuplecreated withrename=True. The renamed fields were applied to_fieldsand to theclass body, but the instance kept the field names as written, so an instance
of
namedtuple("Tuple", "abc def", rename=True)was inferred as having adefattribute instead of_1, and duplicate field names collapsed intoa single attribute instead of being renamed.
Closes #242
v4.3.0Compare Source
What's New in astroid 4.3.0?
Release date: 2026-08-07
Version 4.2.0 was skipped: a
v4.2.0tag was created by mistake during anaborted release attempt, so the changes from the
4.2.0betas are releasedas
4.3.0.Fix a crash on a functional
namedtuplewhose field name changes under NFKCnormalization, such as
namedtuple("mu", ["µ"]). Python normalizesidentifiers, so the parsed class stores the field under
"μ"while thebrain looked it up as written, raising
KeyErroron a definition thatnamedtupleitself accepts.Closes pylint-dev/pylint#8746
Fix inference of a method's first argument (
selforcls) when themethod's return value is stored on an unrelated object. This avoids inferring
clsas the caller's class when indexing a tuple returned by aclassmethod such as
A.c()[0].Closes pylint-dev/pylint#11101
super()with no argument now resolves against the class of the object themethod was called on, instead of the class the method is written in. One consequence
is that a
typing.Selfreturn value survives a chain ofsuper()calls.Closes #2852
Closes pylint-dev/pylint#10807
typing.overloadstubs no longer shadow the implementation when a specialmethod is looked up in the MRO.
Closes #2448
Fix a crash when the field names of a functional
Enumornamedtuplecall are bytes, as in
Enum("", b""). Such a definition is invalid, soinference now falls back to its default instead of raising
TypeError.Closes #3189
Fix a crash when the body of a
typing.NamedTuplesubclass contains anassignment whose target is not a single name, such as
cat.color = "black",basket[0] = "apple"orapple, banana = "red", "yellow". The names boundby unpacking are now copied to the inferred class as well.
Closes #3190
Fix a crash when a binary operation involves a class whose metaclass is not a
class, as in
class C(metaclass=sum)followed byC | None. The type ofsuch a class is a function, which has no bases, so
has_known_bases()nowreturns
Falsefor anything that is not a class.Closes #3191
Fix a crash when a dataclass inherits from a dataclass that annotates
__init__as a field, as in__init__: int. Such a base binds__init__to a name instead of a function, so it no longer contributesarguments to the generated
__init__.Closes #3200
The documentation build now fails on any Sphinx warning, so a cross-reference
that does not resolve is caught by CI instead of quietly rendering as plain
text.
Uninferable,Positionand theBadOperationMessageclassesare documented as part of the public API, and a number of docstrings that
Sphinx could not parse were repaired.
The
>>>examples in the documentation are run when the documentation isbuilt, so one that stops being true is noticed. Most of them could not run
before: they printed node addresses recorded in 2018, and the multi-line ones
were missing the
...continuation prompt. The example forDecoratorsreported the wrong line numbers.
Fix the example in the docstring of
BoolOp, which showed the node it wascopied from:
astroid.extract_node("a and b")gives aBoolOp, not aBinOp.Names written between single backticks in the ChangeLog render as code again,
rather than as italics.
Prevent crashes while processing extension-module classes whose bases cannot
be resolved when applying enum inference transformations.
Closes pylint-dev/pylint#11179
The API documentation now covers the proxies, the objects with no node of
their own, the inference context, the manager, the object models and the
extension call signatures. The
EvaluatedObject,Interpolation,NamedExprandTemplateStrnodes were missing from the list of nodesand are listed now.
Add
__required_keys__and__optional_keys__to the inferredTypedDictbase class, so subclasses no longer raise ano-memberfalse positive in pylint when accessing those attributes at runtime.
Closes pylint-dev/pylint#10158
Comprehension conditions now constrain the inference of names used in the
comprehension, like
ifstatement conditions already did:[x for x in lst if x is not None]no longer infersNoneforxin the element expression.
Refs #3094
Fix
isinstance()constraints only filtering the first inferred value ofa variable: checking a value made the
isinstanceclassinfo uninferablefor the checks of the following values.
Remove Python 2 era dead code and outdated comments.
Notably: the internal
TreeRebuilderconstructor no longer takes aparser_moduleargument.Refs #3154
Fix inference of a starred target that is not last in a
forloop, such asfor a, *b, c in .... The elements following the starred one were countedfrom the target's own arity rather than from the end of the iterable, so
bwas truncated whenever the iterable was longer than the target.Add
qname()method to theSlicenode class, returning"builtins.slice", so that the node can be used in contextsthat require a qualified name (e.g. pylint's
basic_checker).Closes #3115
Add brain tip for
numpy.fromfileso that calls tonp.fromfile(...)are correctly inferred as returningnumpy.ndarrayinstead ofUninferable.Closes #600
Add brain for
decimalthat gets applied if_decimalisn't available.Removed the
**kwargsargument from allinferfunctions.Users upgrading their
astroidversions should ensure they do no pass values other thancontexttoinfer.Deduplicate keys when inferring
dict.fromkeys.dict.fromkeys("aab")now infers a dict with keys
"a","b"instead of"a","a","b", matching the runtime. This also stopsdict.fromkeysfrommaterializing one
Constnode per character for a repeated string such asdict.fromkeys("x" * 10 ** 8), which is a single-key dict.Bound str/bytes and list/tuple concatenation (
a + b) during inference.Bound oversized old-style (
%) string/bytes formatting during inference.A tiny literal such as
"%1000000000d" % 1made_infer_old_style_string_formattingeagerly build a multi-gigabyteConstwhile inferring otherwise untrusted source. The width andprecision are now read out of the conversion specifiers (including
*fields) and the interpolation infers as
Uninferablepast1e8,mirroring the repetition, concatenation and
str.formatcaps. Bytes%formatting is routed through the same handler so it is bounded too;small format strings keep inferring their exact value.
Fix crash (
TypeError: 'UninferableBase' object is not iterable) in themultiprocessingbrain when a local package shadows the stdlibmultiprocessingmodule.Closes pylint-dev/pylint#10014
Bound the number of nodes built when inferring
list/set/tuple/frozensetanddict.fromkeysfrom astr/bytesconstant. Thesebuilt one
Constnode per character with no cap, so ``list(("a" * 10 ** 8)(concatenation is not size-bounded) materialized hundreds of millions of nodes. They now fall back to the default inference past1e8`` characters,matching the sequence-repetition guard.
Refs #3127
Bound string/bytes multiplication (
"x" * n) and integer left shifts(
1 << n) inconst_infer_binary_opthe same way list/tuplemultiplication and
**already are. Inferring a constant such as"A" * 10 ** 10previously materialized the multi-gigabyte resulteagerly; these operations now infer as
Uninferablewhen the resultwould be oversized.
Refs #3107
Bound the field width and precision when inferring
str.formatcalls.A template such as
"{:>2000000000}".format("x")(or a width/precisionsupplied through a nested
{}field) previously built the paddedmulti-gigabyte string eagerly during inference; such calls now infer as
Uninferablewhen the field size would be oversized.Refs #3131
Remove the
asnamekeyword argument fromImport._inferandImportFrom._infer. The alias-to-real-name translation thatasname=Trueperformed is now hoisted intoImportNode._infer_name,which runs in
_infer_stmtsbefore_inferis dispatched. Directcallers of
Import.infer/ImportFrom.infer(previously theasname=Falsepath) now consistently resolve the lookup name as-is.The two flows used to collapse into a single inference cache entry
because the
asnamekwarg was not part of the cache key, so thesecond call returned the cached result of the first regardless of
which one ran. With the translation hoisted upstream, the two flows
set different
lookupnamevalues and therefore land on distinctcache keys, eliminating the collision.
Refs pylint-dev/pylint#10193
Closes #3007
Avoid materializing a multi-gigabyte string while inferring a small literal
such as
"{:>2000000000}".format("x")orf"{1.5:.2000000000f}"._infer_str_format_callandFormattedValue._infernow yieldUninferablewhen a format spec asks for a width or precision over 1e8,mirroring the sequence/repetition caps in
astroid.protocols.Refs #3108
Fix uncaught
IndentationErrorwhen parsing code whose lines end in\r: the slice of source tokenized to compute a class or functionpositionis split on\nonly and could be misaligned with the ASTline numbers. Such nodes now simply have no position information, as
already done when
tokenizeraisesTokenError.Closes #3091
Support PEP 810 lazy imports (new in Python 3.15).
ImportandImportFromnodes gain anis_lazyinteger attribute, mirroringthe
astfield of the same name.Support PEP 798 comprehension unpacking (
{**d for d in dicts},new in Python 3.15).
Fix astroid bootstrap crash on PyPy 7.3.22 (
TypeError: expected str, got getset_descriptor object) by also catchingTypeErrorfromgetattr(obj, alias)inInspectBuilder.object_build. PyPy 7.3.22raises
TypeErrorinstead ofAttributeErrorfor unset getsetdescriptors like
types.FunctionType.__text_signature__, which made_astroid_bootstrapping()blow up on any call into astroid.Refs pylint-dev/pylint#10999
Shorten
import astroidby deferring imports only needed on cold paths.logging(used bymodutilsandraw_buildingsolely to reportstderr/stdout captured while importing a module) and
pprint(used onlyto format debug
__repr__/repr_treeoutput) are now importedlazily, and
astroid.exceptionsimportsastroid.typingunderTYPE_CHECKING.Fix
AttributeErrorcrash instarred_assigned_stmtswhen a starredunpacking target is an attribute (e.g.
for *o.attr, x in ...) ratherthan a simple name.
Closes #2646
Fix
AttributeErrorcrash in theArgumentsassigned_stmtsprotocol when called without an inference context (the public
assigned_stmtsAPI defaultscontexttoNone). Resolving afunction's first parameter dereferenced
context.boundnodewhile thematching
context and ...guard a few lines below was missing; it nowdegrades to Uninferable.
Fix
AttributeErrorcrash inClassDef.infer_call_resultwhen calledthrough the public API without a context (it defaults to
None) for aclass whose metaclass defines
__call__: the callee was assigned tocontext.callcontext.calleewithout checking that a call context exists.It is now guarded, matching the surrounding code.
Wrap assignment expressions (
:=) in parentheses when emittingas_stringoutput so the rendered code remains syntactically valid incontexts such as comparisons, where Python requires the walrus expression
to be parenthesized.
Closes #2668
Catch
MemoryError/RecursionError(andValueError) when validatingtype comments with
ast.parse. Pathological type comments produced byfuzzers (e.g.
# type: i{{{{{{{...) previously crashed parsing with aMemoryErrororRecursionErrordepending on the runtime; astroid nowtreats them as invalid type comments and skips them, mirroring the f-string
fix from #2762.
Closes #2993
Bypass
__init__inInferenceContext.clone()and write the slotsdirectly.
clone()is called ~85k times per pandas/frame.py pylint run;skipping the conditional defaults shaves measurable time off the hottest
constructor in inference.
Refs #1115
Fix
TypeErrorinbrain_randomwhenrandom.sampleis called with asequence containing nodes whose
__init__does not acceptlineno(e.g.
Module). The clone helper now filters init params to those theclass actually accepts.
Closes #3043
Fix
RecursionErrorin_compute_mro()when circular class hierarchiesare created through runtime name rebinding. Circular bases are now resolved
to the original class instead of recursing.
Closes #3023
Closes pylint-dev/pylint#10821
Changed
block_rangeto considerelseits own block, allowingpylintto applydisables to just the block.
References pylint-dev/pylint#872
Fix uncaught
TokenErrorwhen building a class or function whose sourceslice is malformed.
tokenize.generate_tokensmay raise (e.g. on anunterminated bracket on Python < 3.12); position computation now treats such
a node as having no position information instead of crashing.
Closes #2527
str()of a constant argument now infers the actual string value insteadof always inferring
"". When every inference path of the argumentresolves to
Constvalues that stringify to the same string,infer_strreturns that string; otherwise it keeps falling back to
Const("").Closes #2994
Fix
AttributeErrorcrash when looking up a special method on a classwhose explicit metaclass infers to a non-class node (e.g. a function). Such
a metaclass has no MRO, so the dunder lookup now raises
AttributeInferenceErrorinstead of crashing.Closes #3063
Fix
AttributeErrorcrash inClassDef.getitemwhen__class_getitem__resolves to a non-callable node (e.g. an
AssignName).getitemnowraises
AstroidTypeErrorin that case, consistent with its documentedbehaviour.
Closes #3064
Fix
DuplicateBasesErrorcrash in the enum brain when inferring an enumclass with duplicate bases (e.g.
class C(enum.Enum, enum.Enum)).infer_enum_classnow catchesMroErrorand leaves such a malformedclass untransformed.
Closes #3065
Fix
InferenceErrorcrash inClassDef.slots()when__slots__isdeclared as an annotation without a value (e.g.
__slots__: None). SuchConfiguration
📅 Schedule: (in timezone Europe/Paris)
* 0-4,22-23 * * 1-5)* * * * 0,6)🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR was generated by Mend Renovate. View the repository job log.