6

I have a python class with several init variables:

class Foo(object):
    def __init__(self, d1, d2):
        self.d1 = d1
        self.d2 = d2

Is there a way to create this code automatically in PyCharm, so I don't have to type explicitly:

self.dn = dn

This pattern happens very often in my code. Is there a better (Pythonic) way to initialize classes?

I have already seen this post ( What is the best way to do automatic attribute assignment in Python, and is it a good idea?), but I don't want to use a decorator as it makes the code less readable.

Community
  • 1
  • 1
motam79
  • 3,542
  • 5
  • 34
  • 60

3 Answers3

6

You can start by making a custom Live Template. I'm not sure about whether you can auto-generate variable number of arguments this way, but, for two constructor arguments the live template may look like:

class $class_name$:
    def __init__(self, $arg1$, $arg2$):
        self.$arg1$ = $arg1$
        self.$arg2$ = $arg2$
$END$

This is how I've set it up in PyCharm:

enter image description here


Or, you can change the way you set the instance attributes and generalize it for N arguments, see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
5

I learned of another way to solve this.

  • Move cursor to argument
  • Press alt + enter
  • Select Add field '[arg]' to class for single arg -or-
  • Press right arrow key to open sub menu
  • Select Fix all 'unused local' problems to add all args

enter image description here

Marcel Wilson
  • 3,842
  • 1
  • 26
  • 55
0

Partially answering my own question:

Very handy thank you. In version 2020.2 the "Fix all" option is gone. Anyone knows how to add it back?

I haven't found a way to add the missing option back, but a workaround that will accomplish the same, adding all missing fields to the class.

The answer comes from this post: https://stackoverflow.com/a/62060345/1067293

  • Place the mouse cursor over an unused argument and hit Alt+Enter.
  • Then hit the right arrow and select "Run inspection on..."

Run Inspection on...

  • On the new floating window select the file scope.

enter image description here

  • The inspection panel will appear on the bottom.
  • On the left select the file.
  • Then on the right, click the "Add field to class" button.

enter image description here

It's a little bit too elaborate, but nonetheless comes in handy when you've more than a few args.

Ramon Royo
  • 155
  • 1
  • 3
  • 16