Repository navigation
Narrow bare Final for reachability, give static conditions literal types - #12057
crypt0lith wants to merge 5 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.
🔴 Pyright CLI QA —
|
|
The first finding in #12057 (comment) (run: e7312d1) isn't new behavior -- it is in fact one of the oldest. def check(TYPE_CHECKING: bool) -> None:
x = TYPE_CHECKING
reveal_type(x)This PR applies that conversion to every expression, not only the right side of an assignment, so the argument case now shows it too. |
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.__bool__returnsLiteral[False].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.evaluateStaticBoolExpressionreads any name spelledTYPE_CHECKINGasTrue, whatever it refers to.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.__bool__or__len__.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. A name spelledTYPE_CHECKINGcounts only when it refers to typing'sTYPE_CHECKINGor to a variable assignedFalse, as in ty.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.renameneeds to be considered, not whether it's abool, since an argument of another type is already reported by argument checking.and/orand the ternary.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]func5boolparameter namedTYPE_CHECKINGstaysbool, also undernotfunc6TYPE_CHECKING = FalseisLiteral[True]Cases added to
ternary1.pyfunc1func2func3booltest, both branches' typesfunc4__bool__returnsLiteral[False], false branch's typefunc5func6__bool__and__len__, true branch's typefunc7__bool__returnsLiteral[True]and that defines__len__, true branch's typeCases 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 6843464.
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
Static conditions are
Literal[True]orLiteral[False]in any expression, and a ternary whose test is constant has only that branch's type. Types widen only where main's were wrong: aboolnamedTYPE_CHECKINGthat doesn't refer to typing's, which main gaveLiteral[True]when assigned, and the falsy branch for a class object whose metaclass makes it possibly falsy.Author responsibility
Read the AI contribution policy and confirm before submitting: