Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create non-existent functions by a single click in VS Code Python

Other IDE's like PyCharm, IntelliJ, etc. have a feature where if it finds a function being called that is undefined, you can right-click it and click 'create method' or something similar to automatically create the function definition. It helps out a lot in TDD. Is there something similar in VS Code?

like image 922
Zohair Ul Hasan Avatar asked Jun 20 '26 15:06

Zohair Ul Hasan


2 Answers

You can install the My Code Actions extension, here is a simple example:

Configure in settings.json file:

// settings.json file
{
    "my-code-actions.actions": {
        "[python]": {
        "create new methond {{diag:$1}}": {
            "diagnostics": ["\"(.*?)\" is not defined"],
            "text": "def {{diag:$1}}():\n    pass\n",
            "where": "afterLast",
        }
        }
    }
}

The effect when writing code after saving this setting:

enter image description here

enter image description here

enter image description here

Another method that might be useful:

open in sequence File > Preferences > Configure User Snippets. Select python in the command palette. This will create a python.json file in which you can customize the code segment according to the rules.

A simple example:

    "Print to console":{
        "prefix": "defHello",
        "body": [
            "def Hello():",
            "${1:    }print('Hello worle')",
            "$2",
        ],
        "description": "print hello world"
    }

enter image description here

enter image description here

like image 89
JialeDu Avatar answered Jun 23 '26 03:06

JialeDu


At the moment, there's nothing like this built in to the Microsoft Python extensions, but a request for it is in the backlog for Pylance: Add support for create function, class or parameter code actions depending on context #5368. You'd then be able to use the quick fix menu (ctrl/cmd+.). I suggest that you give that issue ticket a thumbs up to show support for it. You can also subscribe to it to get notified about discussion and progress. Please avoid making noisy comments there like ones that just consist of "+1" / "bump".

like image 22
starball Avatar answered Jun 23 '26 03:06

starball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!