Anton Rodenhauser
Anton Rodenhauser

Reputation: 501

hotkey/hotstring to print last variable/all defined variables in PyCharm?

In Intellij for java I can type soutv + tab and it will expand it to System.out.println("var1 = " var1 ", var2, " = ", var 2)

etc.

Is there someting equivalent in PyCharm for python?

A hotstring that I type so it automatically creates something like print("var1=", var1, ...) ?

(in IntelliJ for java there is also sout, soutm, soutp etc.. again: equivalent in PyCharm for python?)

Upvotes: 4

Views: 200

Answers (2)

Josiah Yoder
Josiah Yoder

Reputation: 3756

It is actually quite possible to define a Live Template with the equivalent of soutv for Python. I call mine printv.

  1. Go to settings, search for live templates.
  2. Select a live template under Python and click the small plus in the top left corner above the list of live templates.
  3. Select Live Template from the dropdown menu
  4. Give the template a name, e.g. printv
  5. Give the template a description, e.g., Like soutv, but for Python,
  6. Use this template text print('$EXPR_COPY$:',$EXPR$)
  7. On the right of the template text, click the Edit Variables... button.
  8. With the EXPR_COPY line highlighted, click the down arrow to move this line down below EXPR
  9. At the end of the EXPR_COPY row, check "Skip if defined".
  10. In the EXPR_COPY's Expression field, enter escapeString(EXPR). It should now look like this: Edit Template Variables Dialog
  11. Press the enter key twice to enter this value and exit the Edit Template Variables dialog.
  12. Click on the blue Define word below the Template text.
  13. Check beside Python. It should now look like this: Settings Live Template Dialog
  14. Click OK to exit the Settings dialog.

Now type printv and press the tab key to enable the template. It should behave just like soutv, but for Python.

JetBrains provides documentation on live templates that defined the escapeString(...) function used here. Another answer provided the EXPR_COPY and EXPR variable names.

Upvotes: 2

Slam
Slam

Reputation: 8572

All of this is live templates.

I believe, the difference is that all python is runtime, so you can't really build namespace/scope while writing the code. What you can do, tho, is to create live template like this:

print([f'{name} = {value}' for name, value in locals().items()])

enter image description here

Now you can use plocals + tab to insert line of code that will print out all variables in local scope

Note: formatting is for py 3.6+, but that's just for illustrative purposes

Upvotes: 2

Related Questions