microsoft / pylance-release

Documentation and issues for Pylance
Creative Commons Attribution 4.0 International
1.72k stars 766 forks source link

Feature: "Add Explicit Type Annotation" code-action #4970

Open laundmo opened 1 year ago

laundmo commented 1 year ago

Sometimes, especially when writing libraries, explicitly annotating types which pylance can usually just infer is wanted.

I propose making a code-action show up whenever the cursor is at a place where a type annotation could be inserted (behind a variable name, between a functions closing parentheses and colon) which inserts the type pylance already knows as a explicit annotation.

| is the cursor

def function()|:
    return "test"

becomes

def function() -> str:
    return "test"
laundmo commented 1 year ago

(uhm, this was a feature request. i clicked the feature request button. idk what "needs repro" is doing here)

burcam commented 12 months ago

If I understand what you're looking for, enabling the setting python > analysis > inlay_hints is close. Example: Screenshot from 2023-11-10 13-33-42

laundmo commented 12 months ago

inlay hints is close, yes, but its a result of the type checking, not a input.

writing the type to the file makes sure that if it ever changes, the typechecker would complain. inferring types is great, but the issue is that a different function entirely might change the return type of this one, which i want to catch.

of course, i can just write the type myself, but having a action do it for me is very nice.

or maybe this issue is a reflection of me getting spoilt by the Rust LSP, Rust-Analyzer, which has a LOT of these sorts of conveniences.

debonte commented 12 months ago

inlay hints is close, yes, but its a result of the type checking, not a input.

@laundmo, as the tooltip in the screenshot indicates, you can double-click an inlay hint to write its annotation into the file. Would that be sufficient, or do you feel a code action would be better?

laundmo commented 12 months ago

oh, i didn't even notice the tooltip. i MUCH prefer a code action because it dowesn't need the mouse at all.

alexjbest commented 7 months ago

+1 for having this as a code action in addition to a clickable

TheVayt commented 2 weeks ago

Looked everywhere to find a keyboard shortcut to insert an inlay hint in vscode without using mouse, couldn't find it. Adding a code action to insert it would work for me