Repository navigation
Narrow bare Final for reachability, give static conditions literal types - #12057
Open
crypt0lith wants to merge 3 commits into
Open
crypt0lith wants to merge 3 commits into
crypt0lith wants to merge 3 commits into
Conversation
Reachability narrows a condition's reference only when its symbol has typed declarations, which excludes a bare Final, and never for a module member access. Accept a Final assigned a value in its declaration, imported or as 'module.NAME', and classify a branch pruned by a Final with a literal type as a static condition. Fixes microsoft#11980
A statically evaluated condition received a literal type only as the right side of an assignment, so 'sys.platform == "win32"' was bool as an argument or an operand. Assign the literal type wherever a bool-typed name, member access, unary or binary operation evaluates statically, and remove the assignment special case.
This branch has not been deployed
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.
Summary
Fixes #11980
Supersedes #12002, #12016, #12040
Pyright handles static conditions inconsistently depending on the context.
Final[...]. A bareFinaldeclaration is skipped, even though the assigned value's inferred type isLiteral[False]/Literal[True]. DeclaredFinal[...]static conditions are also skipped during reachability checks when the name is imported.boolinstead ofLiteral[False]/Literal[True].bool-typed parameters of special constructs (namedtuple'srename, dataclass anddataclass_transform), as well as for ternary tests.ty 0.0.107 and pyright 1.1.414,
--pythonplatform LinuxHow ty handles some of these cases:
renameby truthiness of its type: types/infer/builder/named_tuple.rs#L420-L422Root cause
Finalhas none:Finalis a qualifier, so its type is inferred from the assigned value. An imported name has none either, since its declaration is the import, andmodule.NAMEisn't a name. When the check does find the branch unreachable, aFinalwith a literal type is reported byreportUnreachable, unlike the inline static condition.bool.rename, the dataclass anddataclass_transformparameters and the ternary test are evaluated withevaluateStaticBoolExpression, which only reads syntax. An argument of typeLiteral[True]orLiteral[False]is ignored by namedtuple and dataclass,dataclass_transformreports it as not statically evaluated, and the ternary evaluates to both branches.Fix
Final, an imported name and a module member access (module.NAME), as for a local name with a declared type. When aFinalwith a literal type makes a branch unreachable, treat the branch like one under an inline static condition, whichreportUnreachabledoesn't report.bool. Replaces the assignment-only conversion.renamewhen it's always truthy, the dataclass parameters when it's a constantbool, and the ternary's branch when the test is constant. TypedDicttotalandclosedstay syntactic, since the spec allows only literalTrueorFalsethere.Test
Cases added to
staticExpression4.pyfunc1Finalplatform check, branch prunedfunc2Finalplatform check, branch prunedfunc3notof an importedFinalplatform check, branch prunedfunc4Finalplatform check imported withas, branch prunedfunc5Final[Literal[False]], branch prunedfunc6module.NAMEFinalplatform check, branch prunedfunc7Finalwhose value isn't static, branch reachablefunc8Final, branch reachablefunc9Finalclass attribute read through an instance, branch reachablefunc10Anyparameter named like the module, branch reachablefunc11isinstanceon aFinalwith a non-literal type, branch reachablefunc12module.NAMEread before the module name is rebound, branch prunedfunc13module.NAMEread after the module name is rebound to an instance, branch reachableCases added to
staticExpression5.pyfunc1os.name,TYPE_CHECKINGandnotchecks are literalfunc2orwith a true static condition isLiteral[True]func3func4Literal[True]Cases added to
ternary1.pyfunc1func2func3booltest, both branches' typesCases added to
namedTuple9.pyNT6renamefrom aFinaltrue, keyword field renamedNT7renamefrom aFinalfalse, keyword fieldCases added to
dataclass6.pyClassCfield(init=)from aFinalfalse, field passed to__init__Cases added to
dataclassKwOnly1.pyDC7field(kw_only=)from aFinaltrue, field passed positionallyCases added to
dataclassFrozen1.pyDC7frozen=from aFinaltrue, field assignedCases added to
dataclassTransform1.pyCustomer4frozen_default=from aFinaltrue, field assignedcreate_model_frozen3frozen_default=whose value isn't staticIn
typeNarrowing1.py,maybeis now a non-literalbool, since it was never reassigned and its ternaries now select one branch. IntupleLiteralInference5.py, the ternary inconditional_controlnow has only the selected branch's literal, so appending("",)is an error.Evidence and validation
Baseline and head revisions: 2981f9f and e7312d1.
Commands and configuration:
--type-checker pyright --output concise --old 23aa785c7 --new c9f05ea71, on projects that usesys.platform,sys.version_info,os.nameorTYPE_CHECKINGoutside a plainiforeliftest.srcwith its venv, 5 rounds per build;staticExpression3.py,staticExpression4.pyandstaticExpression5.pywith--pythonplatform Linux, 30 runs per build.Tests and checks run: jest on the tests for every changed sample and the other static condition, namedtuple and TypedDict tests; prettier, eslint and tsc.
Observed results:
Limitations or unrun checks: Candidates with matches that weren't run, for disk space: bokeh, dd-trace-py, ibis, prefect, rotki, streamlit and zulip.
🤖 AI-assisted validation
Type precision and performance
No type widens. Static conditions are
Literal[True]orLiteral[False]in any expression, and a ternary whose test is constant has only that branch's type.Author responsibility
Read the AI contribution policy and confirm before submitting: