2

I'm using VS Code for Python projects.

When I write:

class User:
    def __init__(self, name, age, group=None):

I want VS Code to autocomplete the following:

class User:
    def __init__(self, name, age, group=None):
        self.name = name
        self.age = age
        self.group = group

Is this possible with VS Code? I've seen some other editor do this. Is there an extension for this? Thanks a lot!

Gama11
  • 31,714
  • 9
  • 78
  • 100
Zilong Li
  • 889
  • 10
  • 23
  • 1
    https://stackoverflow.com/a/58228253/9938317 You need to modify the snippet a bit for a Python class – rioV8 Aug 05 '20 at 03:02

2 Answers2

4

I have made a Python version with attribute initializers based on the class init snippet by Mark

  "Class Initializer": {
    "prefix": "cinit",
    "body": [
      "def __init__(self, $1):",
      "${1/([^,=]+)(?:=[^,]+)?(,\\s*|)/\tself.$1 = $1${2:+\n\t}/g}"
    ],
    "description": "Class __init__"
  }

I use spaces for indenting and in another snippet \t is transformed to spaces.

If the tabs are not expanded properly, substitute \t with the proper number of spaces. (there are 2 \t).

After typing class name: Enter you are indented 1, then type the prefix cinit.

rioV8
  • 24,506
  • 3
  • 32
  • 49
1

I was trying to do the same thing, found your answer, implemented it and since I'm learning Regex, though it would be nice to try to generalize for atribute typing. Came up with the following:

"Class Defininition": {
    "prefix": "clss",
    "body": [
        "class ${1:ClassName}${2/[(][)]/$1/g}:",
        "\t'''\n\tClass $1: $3\n\t'''\n",
        "\tdef __init__(self, ${4/([^self \\s]*|)/$1/g}):",
        "\t\t${4/(^\\w+|(?<=,\\s)\\w+)(.*?,\\s|:.*|=.*|$)/self.$1 = $1${4:\n\t\t}/g}",
        "\t\t$0"
    ],
    "description": "Initialize Class"
}

The sequence is:

$1 - Class name (also fills default docstring)

$2 - Inheritance (need to type in the parentheses. Here I wanted to set them as default, and remove it if empty. I know it still works with empty parentheses, but I couldn't make it delete if empty and not typed inside $4)

$3 - Class description

$4 - Attribute declaration, including typing following the syntax in Support for type hints

Example:

class ClassName:
    '''
    Class ClassName: 
    '''

    def __init__(self, foo, bar: int, baz, default=10):
        self.foo = foo
        self.bar = bar
        self.baz = baz
        self.default = default
Liu Jacob
  • 3
  • 2