Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get vs code to auto insert if __name_ ... snippet?

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.

like image 363
matt wilkie Avatar asked Dec 07 '22 09:12

matt wilkie


1 Answers

They were explicitly removed in January 2021 edition: https://marketplace.visualstudio.com/items/ms-python.python/changelog#user-content-2021.1.0-(21-january-2021)

Blame: https://github.com/Microsoft/vscode-python/issues/14781

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. copy paste those snippets
  2. In vscode, File->Preferences->User Snippets. Type python and choose python. A json file will open
  3. Paste all or the specific snippets you want in the file and save
  4. Ctrl+Shift+P 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"],

like image 199
User Avatar answered Jan 21 '23 05:01

User