Repository navigation
Closed
Labels
enhancementNew feature or request
Description
Language-server and batch-checker support for Citry templates.
Current foundations
- The parser exposes UTF-8 source spans, scope-level used and introduced variables, slots, and caller-supplied
TagRules. It is still fail-fast and the PyO3 boundary still flattens diagnostics to exception strings. - Citry 0.3.0 shipped the versioned component catalog,
Citry.inspect_component(),Citry.inspect_components(), andcitry inspect --json. - Project selection currently uses the CLI contract
--app module:attribute. A[tool.citry]table is not a current configuration surface. - Runtime registry completeness is the authority for component-aware checks. A static scan is partial and must never produce an unknown-component diagnostic from absence alone.
Accepted implementation path
- Add a conservative
citry checkthat validates base Citry syntax wherever a template region is definite. - Enable registered-component, input, and slot checks only when the configured app imports and discovery completes. Import failure degrades to syntax-only and is reported once as project status.
- Add stable structured diagnostic codes/ranges, expose
HtmlAttr.kind, and add a tested UTF-8-byte to host-source to LSP UTF-16 mapper. - Build a thin diagnostics-first pygls server reusing the checker engine.
- Add narrow component/attribute/slot completion, catalog hover, lexical loop/fill navigation, component navigation at catalog precision, and document symbols.
Extension-transformed templates and alternate *_lang dialects are reported as unsupported until they provide an authored-source analysis mapping. Exact schema-field navigation waits for additive definition locations or a proven static/runtime join.
The detailed accepted design is tracked in docs/design/ide_integration.md.
Metadata
Metadata
Assignees
Labels
enhancementNew feature or request
Activity
JuroOravec commentedon Jul 1, 2026
(Chatgpt export from chatgpt.com/share/68f9fcd9-0bc0-8004-aece-8381111d56f1)
Python type inference options
User: Anonymous
Created:
Updated:
Exported: 7/1/2026 12:57:36
Link: https://chatgpt.com/share/68f9fcd9-0bc0-8004-aece-8381111d56f1
Prompt:
I want to build a linter for vscode similar to Vue's vetur. What are the options for inferring types of variables defined in user's python files?
Response:
Thought for 11s
Great project! In Python you’ve basically got three families of ways to figure out types in users’ files. You can mix these depending on how “Vetur-like” you want your linter to feel (fast, incremental, framework-aware).
===============================================
def f(x: int) -> str: ...,var: Path,typing.cast,assert isinstance(x, T),reveal_type(dev only)..pyiin the project, installed packages with PEP 561 typing, and the global typeshed. Overloads, protocols, generics resolution live here.dataclasses,attrs,pydanticfields,TypedDict,NewType,Enum,Literal,Final,Annotated, etc.isinstance,issubclass,typing.assert_type,if x is None, pattern matching (match/case), guard functions (def is_user(o) -> TypeGuard[User]: ...).=====================================================
Build scopes (module, class, function, comprehension), bind targets (
a=b=c), track imports/aliases, and resolve attributes through MRO/descriptors/dataclass/attrs transformations.Track variable reassignments across branches/loops; narrow on guards (e.g.,
if x:→x != None|False|0|""depending on context).Construct CFG per function; propagate type constraints forward/backward; compute join/meet of unions at merge points.
When calling
fn[T](arg), solve forTfrom argument types and overload signatures (incl.ParamSpec,TypeVarTuple).Track
Literal["GET"], integer ranges for slicing/len() == kin narrow cases; refine containers (list[int]flows fromappend(int)).Accept “duck types” by required methods/attrs; combine with
@runtime_checkablewhen available.Recognize known decorators that transform signatures (
@dataclass,@overload,@functools.wraps) and synthesize the resulting type.==============================================================
Import in a sandbox/venv and read
__annotations__, dataclass fields, Pydantic models. Fast but risky (side effects).Run tests/scripts under a tracer to collect observed types per location; merge with static types as hints (never as the only truth).
Emit
.pyifrom observed types and feed back into the static pass. Good for big dynamic frameworks behind stable test suites.=====================================
Reuse its analyzer via the Language Server Protocol (LSP) and add custom rules on top; or learn from its approach (file-based incremental graph, fine-grained caching).
Use its semantic analyzer/typeshed loader; or call
mypy.apiprogrammatically to get types/diags, then add your lint layer.Heavier setup, great for batch analysis and CFG/dataflow ideas.
Easier to embed for quick symbol/attr inference; weaker on full typing semantics but great for editor UX.
Excellent for building your own passes; LibCST preserves formatting, which is perfect for code actions/fixes.
Pragmatic route: run an LSP that wraps Pyright (for speed + correctness on modern typing) and layer:
Model.objects.filter(...)return types, or pandasDataFrame.groupbychains).===============================
__getattr__at module level → fall back toAnywith opt-in strictness. Provide diagnostics but don’t spam.Model.fieldtypes are properties, notAny.__all__) → build export maps; avoid loading the world.pyrightconfig.json/mypy.ini-like config to trust incomplete stubs.Self,TypeAliasType, PEP 695 generics).==============================================
awaiton non-coroutines, unsafeexcept Exception: pass, incorrectTypedDictkeys, misuse ofOptional,castthat can be avoided,Unionnot narrowed before attribute access.from __future__ import annotations, generate.pyi, addtyping.cast, replacelist()withlist[str]when inferable, add@overloadskeletons.================================
Anybut track provenance (why it becameAny) and surface a single actionable note.=================================
If you tell me your target stack (e.g., Django + pandas) I can sketch the provider interface and a couple of sample rules that query Pyright’s type at a node and emit precise diagnostics/fixes.
Prompt:
How would I use pyright? Say I have a function that returns a literal dict with some keys. How could I use pyright to extract the info on the dict that's being returned from that function?
Response:
Thought for 29s
Awesome—there are two practical ways to “ask Pyright what type this dict literal is” from your VS Code linter:
=======================================================
Run pyright-langserver and query the type at a file/position. The simplest probe is the Hover request; Pyright returns the inferred type as markdown (exactly what Pylance shows on hover).
Flow
pyright-langserver --stdio.textDocument/didOpen(anddidChangeas you edit).textDocument/hoverat the span of your dict literal (or thereturnexpression).dict[str, int]or aTypedDictname).Notes
textDocument/inlayHintto get inferred types for variables/returns.textDocument/typeDefinitionis for jumping to definitions, not a good fit here.======================================================
Use the
pyright-internalnpm package and directly ask the type evaluator for the node’s type. This gives you structured access (e.g., recognize if the inferred type is aTypedDict,Dict[Key, Val], union, etc.).Sketch (TypeScript, conceptually):
Caveats
pyright-internalis not a public API—upgrades can break you. Pin versions, wrap calls, and be ready to update.What Pyright will actually infer for a bare dict literal
dict[key_type, value_type](e.g.,dict[str, int]), not a shape. Pyright does not synthesize a newTypedDictfrom a literal on its own.TypedDict, orTypedDict.So if you need the exact keys from that function, the most pragmatic pattern is:
Then your probe (LSP hover or internal evaluator) will report
UserInfoand you can resolve it to the per-key field map.Putting it together in a VS Code linter
returnexpression).dict[str, Any], consider a code action: “GenerateTypedDictfrom literal and annotate return”.pyright-internalto get the actualTypeobject for the node.TypedDictType, read its fields.dict[K,V], you only know K/V, not concrete keys.Handy diagnostics / code actions you can build
TypedDictwhen returning a dict literal from a public function:TypedDictnext to the function and set-> NewTypeName.Any: if values are all literals (int/str/bool) or uniform, offer to add-> dict[str, int]or generateTypedDict.If you want, I can sketch a minimal VS Code extension snippet that starts
pyright-langserver, sendsHoverto a position, and parses the returned type text—so you can wire it into your lint rule.Prompt:
Ok, suppose I use pyright via LSP and it returns a markdown with 'UserInfo'.
Now let's do something more close to vetur. I guess that it works something like this:
"""
return {
myVar: abc,
}
"""
"""
{{ myVar.item.name }}
"""
"""
// Generated from the returned dict
var1 = abc;
// Paste the js expression
myVar.item.name
"""
Is this how vetur does it? Does it sound correct? Or if vetur does it differently, how do they do it? Lastly, it seems like a workaround, having to construct the dummy code like that. Could we instead simply pass the js expression and context what variables and their types are available?
Show moreShow less
Response:
Thought for 34s
Short answer: yes—your mental model matches how Vue tools do it. Vetur (and today’s Volar) compile template expressions into a virtual TypeScript file, run the TypeScript language service on that file, then map diagnostics/quick-info back to the original template via a source map. Vetur’s docs say this explicitly: compile → sourcemap → run language features on the virtual TS → map results back.
vuejs.github.io Volar generalizes this with first-class “virtual code objects” and a source-map utility.
Yarn+1
So for a Python/Vetur-like linter powered by Pyright over LSP, do the same pattern:
What Vetur/Volar do (confirmed)
setup()/data/props, then inlines each template expression as TS code.<template>node ranges so hover/errors/completions line up in the editor.The Python analogue with Pyright (LSP)
LSP has no “evaluate this expression under this symbol table” RPC. So you must provide a file (real or virtual) that contains both the context and the expression—exactly like Vetur.
Pipeline
TypedDict, great—use that. Otherwise, synthesize one from the literal keys you see (optionally offer a code action to generate it in real code later).py://virtual/<component>/<hash>.py) that declares the bindings visible to the template:abc(from a prior hover/definition in user code), emit it asAbcTypewith an import or a forward reference. If not, fall back toAny(and later offer to tighten types).textDocument/publishDiagnostics(by triggering a Pyright re-analysis)textDocument/hover,completion, etc., at offsets of__probe_k.@expr_k, store the template start/end and the virtual file start offset. Subtract/add to translate positions for all results.Why you can’t “just pass an expression + context” to Pyright
Pyright’s LSP surface doesn’t accept arbitrary environments. It analyzes files in a project graph. That’s why the virtual-file + sourcemap pattern is the standard solution across SFC ecosystems (Vue Vetur/Volar, Svelte, etc.).
GitHub
Practical tips that make this work well
dict[K, V]. If you want per-key errors and hovers, annotate (or synthesize) aTypedDictfor the function’s return.Anyin your context, note it in the diagnostic so users understand why a template expr has weak types (and offer a fix: generateTypedDict, add annotation, etc.).Minimal end-to-end sketch (VS Code side)
pyright-langservervia your extension’s language client.didOpena virtual module containing context + one line per template expression.hoverat the virtual offset; translate back using your source map; render the hint in the template.publishDiagnosticson the virtual file; remap and re-publish them for the template document.If you want, I can draft a tiny sample virtual-file generator and the source-range mapper you can drop into a VS Code extension (TypeScript) to prove this out with Pyright LSP.
Powered by ChatGPT Exporter
JuroOravec commentedon Aug 30, 2026
Implemented. See citry-lsp and VSCode ext