pythonvisual-studio-codetdd

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?


Solution

  • 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