25

How to configure or enable visual studio code to automatically insert the standard:

if __name__ == '__main__':

I see it was implemented in 2018 but the usage being discussed in that ticket does not trigger anything for me. I've been scanning through the docs and general internet but my search keywords are not turning up relevant pages.

1
  • In PyCharm you type main and then hit tab, maybe it'd be the same in VS Code? Just a shot in the dark. Commented Feb 4, 2021 at 16:58

2 Answers 2

57

They were explicitly removed in the January 2021 edition.

Blame this issue: Remove or disable code snippets

All the old python snippets are here: https://github.com/microsoft/vscode-python/blob/2020.12.424452561/snippets/python.json

If you want them back:

  1. In vscode, File -> Preferences -> Configure User Snippets. Type python and choose python. A json file will open
  2. Copy-paste all or the specific snippets you want in the file and save
  3. Ctrl+Shift+P then Reload Window to activate the changes

This is the default main snippet:

    "if(main)": {
        "prefix": "__main__",
        "body": ["if __name__ == \"__main__\":", "    ${1:pass}"],
        "description": "Code snippet for a `if __name__ == \"__main__\": ...` block"
    },

If you want to change or tweak which text triggers the snippet, modify the prefix field. The prefix field can be a string as shown above or a list if you want more triggers:

"prefix": ["__main__", "ifmain", "main", "ifm", "if m"],
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. After copy pasting this for the nth time in a new profile I went and hunted out an extention to make it easier. See the github.com/cstrap/python-snippets
8

See User's answer below, as it's the better answer.


I've noticed the same thing -- I wonder if this snippet was removed, or if its presence depends on the language server used (I believe VSCode switched from MS's language server to Pylance by default).

In any case, you can recreate the extension yourself by clicking the menu item Code > Preferences > User Snippets, select python.json, and then enter the following entry:

"Main": {
    "prefix": "__main__",
    "body": [
        "if __name__ == \"__main__\":",
        "\t${1:pass}"
    ],
    "description": "Insert main block"
}

More info: https://code.visualstudio.com/docs/editor/userdefinedsnippets

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.