Shubham R
Shubham R

Reputation: 7644

Add a function template in PyCharm

I am developing python code in pycharm

I am looking to define a skeleton of function definition in python.

What I am looking for is that each time I initiate a function definition, say:

def func1(arg1,arg2):

and press enter, it should automatically create the below skeleton for me to edit inside of it.

def func1(arg1,arg2):
    try:
        return(1)
    except Exception as e:
        print(e)

Is that possible in PyCharm?

Upvotes: 2

Views: 1677

Answers (2)

Kishor Pawar
Kishor Pawar

Reputation: 3526

Go to file > settings

Once an editor dialogue is opened, expand Editor and select Live Templates as shown in the image below.

enter image description here

Expand preferred option, in your case python here.

Click on the green plus sign at top right corner and select Live Template

Live template selection

After that has been done define Abbreviation, Description, and Template Text as shown below.

Define everything

You would see a warning just below Template Text, you will have to define the context where this template can be used.

See below, select all that is applicable and click apply and ok.

select context

Finally, try typing the Abbreviation wherever applicable and hit enter.

type it

you will see the template as below.

Actual live template

That's it. Cheers.

Upvotes: 5

JGrindal
JGrindal

Reputation: 813

This is absolutely possible - PyCharm has a function called "Live Templates," which you can read more about here. Based on what you're trying to do, the code you would want to define in your "Template text" would look like:

def $name$(arg1,arg2):
    try:
        return(1)
    except Exception as e:
        print(e)
        $END$

You'll have edit your variables (or add more than just $name$ if you want to populate more than just the name) and then, whenever you type def, one of the options on the menu should be your predefined function stub.

The JetBrains documentation goes into more detail in how to do this, as well as troubleshooting things (make sure you define your context as "Python"), but this should be enough to get you up and running. Hope this helps!

Upvotes: 2

Related Questions