5

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!

1

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

May be you had saved the class file in another folder. Because I am working in vs code with python language and now i am trying to learn objects and class and I am also facing the problem that my class in not initiating. Then I saved my class file in same folder and now the problem is solved.

Here i saved the file in same folder named day-20

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.