42 Tips and Tricks
Become an IDE champ with these bite-sized tips and tricks.
Development is about focus and flow. Learning your tool helps you get into the flow and stay there.
This playlist shows a variety of IDE tips and tricks from across the major usages of PyCharm.
Find Actions in Any JetBrains IDE
If you want to do something, but don't remember the shortcut or menu option, use Find Action. Press ⇧⌘A (on Mac) or Control+Shift+A (on Windows/Linux)
The Problem
You want to move a line up. You could use the mouse to select the line, cut it, go to the next line up, and paste it. You know the IDE has an action that can do it, but…what is it?
Let’s use the mouse and look in the Edit menu. Hmm, not there. How about Code? Ahh, yes, it’s there, with the keyboard shortcut. Maybe you speed that up by learning the shortcuts. There’s the Keyboard Shortcuts PDF. You could try memorizing all of that... possibly but nor probable.
The IDE has a lot of power, which means a lot of actions, with new ones coming in each release, not to mention plugins. You’re not going to memorize all of them. Does the IDE have a better way?
The Solution
What you need is Find Action, a single keyboard shortcut to memorize. The one ring to rule them all. Shift-Cmd-A on macOS, Shift-Ctrl-A on Windows and Linux:
Type “move line up” and you’ll see the Move Line Up Action. Bonus: the keyboard shortcut is shown when an action has one.
That’s a lot to type. Instead, use speed typing to type just fragments such as "m | u". Maybe you don’t know the full action name. Just type one word to get in the ballpark such as "type".
One last point: Find Action also matches preferences, and some are inline toggleable. Want to disable tabs without opening settings/preferences? Start Find Action and type ta pl no for the Window | Editor Tabs | Tabs Placement: None preference. Press Enter to toggle it.
Remember…you don’t have to remember! Keyboard shortcuts, that is. Let Find Action be your one-stop-shopping for actions.
Reduce Clutter by Disabling Tools
Save space by turning off various toolbars and Project Tool.
People associate IDEs with busy UIs filled with buttons and knobs and distraction. But that's just the default. It doesn't have to be that way. Once you get oriented, you can turn off everything you don't need and get a lean coding experience.
In this tip we use the View
menu to disable 3 toolbars. We
then take the big step of hiding the Project Tool window, with its
file explorer.
"How will I navigate to my files?" you ask. Later tips will answer that, ultimately with: "You don't." Meaning, you grow out of "files" as a useful place to jump to.
In fact, later tips will show how you can, with the keyboard instead of the mouse, temporarily bring some of those hidden tools back from the dead.
Disable Tabs
Save space and stay keyboard-centric by turning off the tabs.
People love tabs. It's the default way in PyCharm to jump around between the few files you are working on for a task.
But tabs have downsides:
-
Lots of mousing. Sure, you can learn some keystrokes to move between tabs, but they are a visual metaphor, and people instinctively use the mouse.
-
Clutter. Before long you have tons of tabs open and then need other machinery to help deal with tabs...which you used to help deal with files.
In this tip we show turning off tabs as a prelude to other tips related to keyboard-centric navigation. We show navigating through preferences to the action, as well as searching for the action and even setting it in the popup.
How to Quickly Jump to Recent Files in any JetBrains IDE
Are you tired of hunting for that crucial file buried in your project? Say goodbye to the hassle with these IDE shortcuts and tips. Jump to recent files effortlessly in JetBrains IDEs like IntelliJ IDEA, PyCharm, PhpStorm, WebStorm, GoLand, CLion, RubyMine, and more!
The Problem
Have you ever been deep into a project, only to realize that you forgot to include something crucial in a file? We've all been there, so let's learn how to prevent this from happening to us again. While the tabs at the top of your screen are helpful, they can be a little bit overwhelming.
The Solution
Instead of searching for a certain tab, let’s use our IDE. One convenient way to find certain files is using the Recent File Window. It gives you a nice list of all the files you have visited recently. It is automatically sorted in the order you have visited them, which makes going back so much easier
Well, that is already a great improvement, but we can do even better! What if the file you are looking for is at the very bottom. Well sure we could press arrow down like a hundred times, or worse use the mouse, or we just type directly into the window, which lets you search for a particular file.
Wouldn’t it be nice if you could narrow it to only the files you edited, not all you visited? In the upper right corner, you see the “Show edited only” files. This will help you remove some clutter and hides the files you just visited without doing any changes, and you can even open a certain file in a split window to have a look at multiple files at the same by clicking on the icon on the right side or pressing Shift or Enter.
I got one more for you, let’s check it out! If we look to the left side of our Recent Files Window we see all the amazing tools we recently used. You want to jump to the Terminal? Just type in “T-E-R” and it will take you right there.
Development is hard! and having a good overview of edited files is difficult. Luckily our IDEs make navigation really convenient!!
Navigate to Symbol
Navigate your project by code, not files.
Decades of old habits make us think of files, with their deeply-nested locations and obscure, inconsistent file names and extensions. Our brains are already full. Who has time to memorize all the files in the project?
Don't. Instead, think of the code in your project, not the files.
Want to jump to a class, function, or variable? You have a smart IDE
that's indexed the universe. Put it to work and use the
Navigate by Symbol
action (Shift-Ctrl-Alt-N
, Alt-Cmd-O
on
macOS) quickly, without disruption, get to where you want to go.
When the popup appears, start speed typing to get to the symbol, using the "camel hump" syntax universal to speed searching.
Once you select your choice, PyCharm not only opens the file but puts the cursor on the spot of the declaration of the symbol.
Remember, this isn't just for Python symbols. This matches in JS, CSS, SQL, etc.
Navigate to File
Jump to a file without using the Project Tool and your mouse.
Navigating your project files is a chore. Expanding folders and subfolders, scrolling, double-clicking. It breaks your flow and makes you think about administrivia.
Wouldn't it be great if your tool knew everything about every file, and let you just jump to things by typing?
The Navigate to File
action (Shift-Ctrl-N
, Shift-Cmd-O
on macOS) makes this actually...fun. The non-disruptive popup
appears and you just start typing parts of the filename until you
see the file you're looking for. No trees, no mouse.
Use the same hump-case "speed search" syntax to filter the listing with parts of filename fragments. Use slashes to indicate that a file should be in part of the directory structure. Click the checkbox to look outside of your project files, into your dependencies.
If you want to jump to a file, Navigate to File
is a speedy,
non-disruptive option.
Navigate Cursor Position Back and Forth
Easily navigate back to where you were, or where you went.
Decades of old habits make us think of files, with their deeply-nested locations and obscure, inconsistent file names and extensions. Our brains are already full. Who has time to memorize all the files in the project?
Don't. Instead, think of the code in your project, not the files.
Want to jump to a class, function, or variable? You have a smart IDE
that's indexed the universe. Put it to work and use the
Navigate by Symbol
action (Shift-Ctrl-Alt-N
, Alt-Cmd-O
on
macOS) quickly, without disruption, get to where you want to go.
When the popup appears, start speed typing to get to the symbol, using the "camel hump" syntax universal to speed searching.
Once you select your choice, PyCharm not only opens the file but puts the cursor on the spot of the declaration of the symbol.
Remember, this isn't just for Python symbols. This matches in JS, CSS, SQL, etc.
Activate Navigation Bar
Bring up the Navigation Bar as needed, let it disappear when finished.
Getting into the flow means stripping down your UI distraction (turn off the
Project
window and Navigation Bar
) then going keyboard-centric to avoid
the mouse. But you still need to get to your files, and sometimes you'd prefer
to browse instead of use Recent Files
or the Find File
action.
If you've uncluttered your UI by hiding the Navigation Bar, bring it back on demand.
Use Navigate -> Jump to Navigation Bar
(Alt-Home
Win/Linux, Cmd-Up
macOS)
to temporarly re-active the Navigation Bar, but as a temporary panel. Once
you use use it, the window disappears.
If you use this tip and temporarily make it appear, how do you make it disappear?
Press Jump to Source
(F4
Win/Linux, Alt-Down
macOS) or just hit Escape
to go back to where you were working.
Perhaps you didn't hide the Navigation Bar. I don't, because I like those other toolbar buttons to the right. But still, you'd like to use it without the mouse. Activating the Navigation Bar still helps, as it moves the focus out from the editor and up to the Navigation Bar, where you can then use your cursor keys.
How did we hide it in the Navigation Bar first place, or bring it back if wanted?
The View
menu's Navigation Bar
item is a toggle. Want a faster, keyboard-centric
way to toggle? Find Action
(Shift+Ctrl+A
Win/Linux, Shift+Cmd+A
macOS) lets
you search for such settings and even toggle inline. Type vi nav
to speed search,
make sure the selection is on View: Navigation Bar
, then press enter. The
setting is toggled...no mouse usage needed.
Navigate Files With Navigation Bar
Move around your project tree and select files, from your keyboard, with the Navigation Bar.
We've discussed "getting into the flow"...strip down the IDE to focus and don't take your hands off the keyboard. But if you've turned off your Project tool window, how can you navigate files and directories?
You could use the Project
action (Alt-1
Win/Linux, Cmd-1
macOS) to bring
back the Project tool, do your work, and then hide it again. Instead,
temporarily bring back the Navigation Bar then navigate it with the keyboard.
You can use the left arrow to go up a directory and right arrow to go down a directory. To see the contents of a directory, either press the down arrow or press enter. With this you can get to any place in the tree, without using the mouse.
For looking at the directory the currently-edited file is in, this is even
easier. Activating the Navigation Bar makes the current file selected. You
don't have to press Left
to select the parent directory. Just press
Down
.
Open File With Navigation Bar
Open a file somewhere in the project tree using the keyboard and Navigation Bar.
If you've closed the Project Tool window and hidden the Navigation
Bar, you need a way to open file that's keyboard centric and doesn't
disrupt your flow. Usually, the fastest way to open a file is the
various search options (Recent Files
, Navigate to File
, etc.)
But other times, you want to browse instead of search.
As shown previously, use the Navigation Bar to select a file:
-
Activate the Navigation Bar with
Navigate -> Jump to Navigation Bar
(Alt-Home
Win/Linux,Cmd-Up
macOS) -
Use the cursor keys to get to the target directory
-
Speed search to select the file
Once selected in the Navigation Bar, press Enter
and the IDE will
open your file. Clicking with the mouse also works.
As a note, this is a very common pattern for jumping to a file in
the current directory. In this case, you don't have to press
Left
to go up to the directory. Even though the current file selected,
you can still press Down
or better still, just start speed searching.
Opening the file isn't the only operation you can do on a selected
Navigation Bar item. You can Refactor This
, delete...basically,
anything you could do when you click on the file in the Project Tool.
We'll see two examples in subsequent tips.
Narrow Navigation Bar With Speed Search
Narrow and select from a long folder listing Navigation Bar by typing a speed search.
We've discussed getting into the flow by reducing UI clutter and being keyboard-focused. We're using the Navigation Bar on-demand to get to targets in our project tree.
When we get a drop-down for contents of a directory, sometimes the listing is long. We don't want to press down arrow a bunch of times. Instead, use the IDEs "speed search" facility to quickly dive through a long listing.
As shown previously, use the Navigation Bar to get to a directory listing:
-
Activate the Navigation Bar with
Navigate -> Jump to Navigation Bar
(Alt-Home
Win/Linux,Cmd-Up
macOS) -
Use the cursor keys to get to the target directory
We now want to select one item in the list, but using speed search:
-
Simplest case: Type one letter
-
Type a second letter...if your choice is selected, then you're done and you can act on it (e.g. press enter,
Ctrl-T
to refactor, etc.) -
Type a period and a letter to search in the file extension
This becomes a very fast workflow for speeding through the navigation bar, all without using the mouse. Moreover, speed search is a pervasive pattern in the IDE.
Create New File With Navigation Bar
Activate the Navigation Bar and create a new file somewhere in the project tree.
How can I create a file if I've turned off the Project Tool? Let the Navigation Bar be your one-stop replacement for the Project Tool.
First, get to the target directory:
-
Activate the Navigation Bar with
Navigate -> Jump to Navigation Bar
(Alt-Home
Win/Linux,Cmd-Up
macOS) -
Use the cursor keys to get to the target directory
-
Speed search to select any subdirectories
Once your target is selected, use New
(Alt+Insert
Win/Linux,
Cmd-N
for macOS) to bring up the new file dialog. Just like in
the Project Tool, the new file is opened after creation.
Also like the Project Tool, your selection doesn't have to be on a directory. If you're on a file, the new file will be created as a sibling. This is particularly useful in the common case of creating a new file in the current directory:
-
Activating the navigation bar higlights the current file
-
Immediately press
New
(Alt+Insert
Win/Linux,Cmd-N
for macOS)
Quite simple: two key combos and you have a new sibling file, with no permanent file tree visible and no popups to close afterwards. That's what getting in the flow is about.
Find In Path With Navigation Bar
Use keyboard and Navigation Bar to find files under a path.
You want to find a file at a path in your project tree. But you've turned off the Project Tool. You could turn it back on, find the file, then turn it back off. But then you'll talk yourself into leaving it visible.
Use the Navigation Bar instead:
-
Activate the Navigation Bar with
Navigate -> Jump to Navigation Bar
(Alt-Home
Win/Linux,Cmd-Up
macOS) -
Use the cursor keys to get to the target directory
-
Speed search to select any subdirectories
Then, when your target is selected:
- Invoke
Find in Path
(Shift+Ctrl+F
Win/Lin,Shift+Cmd+F
on macOS) to bring up theFind in Path
dialog.
Just like you would in the Project Tool. Except, no permanent real estate lost and the Navigation Bar appears/disappears on command. All without touching the mouse.
Add Line After/Before
Smart-add a line, from the middle of a line, after or before the current line.
It's easy to overlook, but we frequently add a line of code while in the middle of another line. Perhaps we were fixing something and want to proceed to the next line. Perhaps we were on an import and want another import on the line above.
It's tempting, for adding a line after, to treat this as a two-step process:
-
Go to the end of the line (ugh, sometimes with the mouse)
-
Press enter
Adding a line above is worse:
-
Go to the beginning of the line
-
Press enter to make space above
-
Press
Up
to go to that new, empty line -
Perhaps press tab a few times to get the indentation right
Instead, use Start New Line
(Shift-Enter
Win/Linux/macOS). With your
cursor anywhere in the current line -- where you are just finishing an
edit -- you can then get an empty next line, with correct indentation.
For a line above, use
Start New Line Before Current
(Ctrl-Alt-Enter
Win/Linux,
Alt-Cmd-Enter
macOS.) You get a new line, indented appropriately for the
language and context.
Make and Extend Selection Using Keyboard
Use the keyboard to select blocks of code then extend/shrink the selection.
In coding, we select code and operate on it. For example, move it to another line, change its indentation, etc.
You can use your mouse to make your selection. Or, use the keyboard.
For example, use
Move Caret to Previous Word with Selection
(Shift-Ctrl-Left/Right
Win/Linux, Alt-Shift-Left/Right
macOS) to (a) move the cursor
forward or backward a word, while (b) expanding the selection along
the way. Want to select three words? Do it three times.
In Python code you frequently want to gradually expand a selection
from where the cursor is at: the symbol, then the substatement,
then the full statement, then the line, then the block, etc.
Extend Selection
(Ctrl-W or Shift-Ctrl-W
Win/Linux,
Alt-Up/Down
macOS) is ideal. It works semantically. Keep pressing it
until you get the selection you want. Go too far? Do the inverse to
shrink the selection.
Without using the mouse.
Finally, PyCharm also supports multiselection aka multiple carets.
Move Block Up/Down Using Keyboard
Use the keyboard to move a line or selection up or down in your file.
We want to operate on code in the editor fast. Using Cut-and-Paste is kinda fast, but there's a better way that doesn't temporarily remove the code from your file.
Make a selection (without using the mouse)
and use (Shift-Alt-Up/Down
Win/Linux, Alt-Shift-Up/Down
macOS)
to move that selection to the target line. The selection gets dragged
along, in view.
With cut-and-paste, you have semi-dangerously remove your code, then make a new line to put place the selection, then paste.
Reformat Code
Tell PyCharm to clean up indentation and other code style in your file.
Perhaps you copy and pasted some code with a different line length than your other code. Or you join a project where the other have sinned against all the gods with their heretical indentation spacing. Tabs?!
PyCharm makes it easy to set code styles in wildly flexible ways (project
vs. IDE, EditorConfig files, inline markers to suppress, etc.)
But PyCharm makes it even easier to apply those code styles with the
Reformat Code
action.
This action has an easy shortcut and can be applied to an entire file, a selection, or across many files in the project. With PyCharm Professional, you can also use it outside of Python, in JavaScript, CSS, etc.
Optimize Imports
Automate the organizing and cleaning up of your Python imports with Optimize Imports.
PyCharm automates many "gardening" tasks when writing Python code. Managing your
imports is one of them: with the Optimize Imports
action, PyCharm cleans
up your imports, using your import style preferences.
For example, Python's PEP 8 section on import style might complain that you have an unused imports, your imports aren't sorted within a group, and you have two top-level imports on the same line. Also, you might set in a project that you'd like to always split imports from the same source.
PyCharm can clean all of that up using Optimize Imports
, which cleans up your
imports based on settings you can save. This action can be run on a single
file or across all files in a project. Also, the Commit
dialog box has
a checkbox to run it in the Before Commit
section.
Finally, PyCharm Professional applies all of this to imports in other languages such as JavaScript and TypeScript.
Generate Imports While Typing
Avoid interruption by letting PyCharm generate your imports as you type.
This is the right way to do imports.
As you are typing a symbol, you have to both finish typing the symbol -- and without a typo -- and you have to import it. For the import, you have to stop what you're doing, scroll up, enter the import in the correctly-sorted PEP8 way, etc.
Let PyCharm do all of that. While typing, press Ctrl-Space Ctrl-Space
to tell PyCharm to autocomplete on symbols from modules. When you select
the completion target, PyCharm will also generate the import -- in the right
place, merging it with an existing import if needed.
Install and import
While typing a symbol, let PyCharm install it and generate the import.
You're writing code and want to import a package, and want PyCharm to generate the import. But you haven't installed it yet. PyCharm can do both.
Type the name of the package and hit Alt-Enter
, then choose Install and Import package
. PyCharm will do both: you'll see a notification during the installation,
then the import will be generated in the right way, according to your project styles.
Extra credit: if PyCharm sees that this new package isn't recorded in your package's
requirements.txt
or Pipfile
, it will generate a warning which you can correct
with -- again -- Alt-Enter
.
Adding Fields In a Constructor
Let your IDE add constructor arguments to your instance.
It's one of those chores...your class has an __init__
with some arguments
and you need to assign them to self
. What a lot of typing.
Let the IDE do it for you. As you type the argument name, hit Alt-Enter
and choose Add 'field' to constructor
, then type the next argument. Or
later, put the cursor on each argument and invoke it. PyCharm will create
the assignment for you.
Rename a File and Its References
Change your mind on a file name and the IDE makes all the changes for you.
You made a file. You tried to choose the right filename. You then used it all over your project.
Now you've changed your mind.
It's sitting there, annoying you, but you can't be bothered to find all the places that use it. Search and replace might find a bunch of false positives. You'd really like something that understood symbols, and just in imports.
Select the file and use
Refactor | Rename
(Shift-Ctrl-Alt-T, 1
Win/Linux, Ctrl-T, 1
macOS)
to change the name of the file and occurrences. This will also adjust VCS.
Best of all, if you change your mind, Undo
puts it all back as one
editor transaction.
Rename Symbol
Change a variable name, class name, or other symbol, across the project.
You wrote a function which you use all over the place in a project. Or a class. The name no longer matches its purpose. But the change is too much of a hassle.
The IDE knows where it is used. Even better, it knows the difference between usage in your project vs. finding it in a dependency, and best of all, usage as a symbol vs. just some letters in a string.
What if the same symbol name is used in two Python modules? Yep, PyCharm can tell the difference and only rename to the appropriate the symbol from that module.
Same for method names. Have the same method in two classes? Refactor Rename
will look in your project for the correct usage and rename it.
Simply put your cursor on a symbol and use
Refactor | Rename
(Shift-Ctrl-Alt-T, 1
Win/Linux, Ctrl-T, 1
macOS.)
Provide the new name, preview the places it found, and select Do Refactor
.
Change your mind? Refactoring is done as a single editor transaction,
meaning Undo
reverts all the places that were renamed.
Quick Documentation
View arguments and documentation without interrupting your flow.
We frequently encounter code that we're not sure about. Other people's code. Heck, even our code. Sometimes we just want the arguments for a function. Other times we want to know positional versus keyword args. Or the types of the arguments. Or their default values. Or a nice rendered docstring.
PyCharm has several facilities for showing you documentation about a symbol.
First, Quick Documentation
(Ctrl-P
Win/Linux, F1
macOS) brings
non-obtrusive inline popup showing all that information, with a hyperlink
where you can navigate to the definition. Press it again and the popup
turns into a tool window which updates for each symbol that you land on.
Always there, always helping...until you want to hide it, like any other
IDE tool window.
Want the full docs in a browser, but don't want to hunt around to find
it? For many popular packages, External Documentation
(Shift-F1
Win/Linux/macOS) brings up a browser on the documentation
page for that symbol.
View Parameter Info
Quickly see function arguments and argument types.
Some functions or classes -- well, let's admit it, they are kind of chatty. They require lots of arguments, have lots of optional keyword arguments, some with default values.
So you stop, go look at the function, and come back to what you were doing.
There's a better way. With your cursor in the parentheses, invoke
Parameter Info
(Ctrl-P
Win/Linux, Cmd-P
macOS.) You get a tiny
popup with the positional and keyword arguments, along with any default
values. Bold is used to mark the current spot in the parameter list that
your cursor is at.
You can invoke this before you type any parameters, after you've typed a few, or later if you come back to make a change.
Run From Keyboard
Use the keyboard to select and run a run configuration.
These tips have a recurring theme: use your keyboard, not your mouse. Running your code should be the same way.
Use the Run
action (Shift-Alt-F10
Win/Linux, Ctrl-Alt-R
macOS) to get
a popup listing your defined run configurations, both permanent and temporary.
You can then use the arrow keys or speed-type to highlight the one you want to
run, pressing Enter
to select and execute it.
"Select" is used intentionally: one you select this run configuration, it is
the active one, and the simpler Run <your configuration>
action
(Shift-Alt-F10
Win/Linux, Ctrl-R
macOS) will immediately run it.
You can do more from the keyboard than just run it. Each entry in the popup has a submenu which you can access by pressing the right arrow. This lets you choose how you want to run it (Run, Debug, Coverage, Profile, Run under the concurrency diagram, etc.) as well as edit that configuration or delete it.
Debugging is popular option, so it gets its own popup sequence. Use the
Debug
action (F9
Win/Linux, Alt-Cmd-R
macOS) to give the popup, but leading
directly to debugging (to skip the submenu step.) Once selected, you can re-run
that debug configuration with the Debug <your configuration>
action
(Shift-F9
Win/Linux, Ctrl-D
macOS.)
Again, for both the run popup and debug popup, don't forget to speed type to select, instead of the arrow keys.
There are, obviously, many other ways to run your code (menus, right click, gutter icons, tool window buttons.) For keyboard-centric folks, give this a try.
Conditional Breakpoints
Speed up your debugging by stopping execution only when you want to.
Debugging? Super-useful. Visual debugging? Super-super-useful. Stepping through a loop until the end, when your problem surfaces? Not so much.
Take a step forward on your debugging zen with conditional breakpoints.
Let's say you have a problem on a line in your code and you want to stop there and see what's happening. But the problem doesn't occur the first time that line is executed. Maybe the line is in a loop, and the problem doesn't occur until the end. Or maybe the line is in a function which gets called 100 times before the function argument value under suspicion is passed in.
Set a breakpoint on the line, then right-click on the breakpoint. You get a dialog to edit the properties of a breakpoint. Meaning, PyCharm breakpoints are richer than just a red circle.
In the Condition
box, type in an expression, such as age > 90
, that
must be true for the breakpoint to be triggered. You can use any variable
in scope at that line, and PyCharm autocomplete works in that box.
When you then debug your code, that line will be passed over until the condition is met. When true, the debugger stops on that line, just like normal.
During difficult (read: insane) investigations, you wind up trying the same thing over-and-over. The field has a drop-down with a history of expressions you've used.
There are other ways to edit a breakpoint's properties, such as the
View Breakpoints
action (Shift-Ctrl-F8
Win/Linux, Shift-Cmd-F8
macOS) which is also a button in the debug tool window. This option
shows all the defined breakpoints.
Evaluate Expression During Debugging
Select your code and execute it, in the right context.
Debugging means poking around, usually at a point in the execution. You set a breakpoint, fire up the debugger, and start pokin'.
Sometimes "poking" means "typing in expressions and seeing the result values." This is where Evaluate Expression helps. It is a popup window where you can type in values and see the results, in the scope of the stopped line: all the values in that block, passed in, etc.
There are several ways to get to the popup:
-
Click the debug toolbar button to launch it
-
Invoke the
Evaluate Expression
action (Ctrl-F8
Win/Linux,Alt-F8
macOS) -
Right-click in the editor and choose
Evalute Expression
Note that, if you have a selection in the editor, that selection is
filled into the Evaluate Expression
input box. This is a very handy
way to stop on a line, then execute part of that line, without retyping
or even cut-and-paste. This also means Evalute Expression
can be
driven with the keyboard instead of the mouse.
As you are typing in the Evaluate Expression
input box, autocomplete
and other features are available. Also, previous expressions you've
typed are available as autocomplete and in the dropdown.
If you type something in that causes a new variable to be defined in that
scope, or changes an existing variable, the Variables
pane will reflect
it. Meaning, you are indeed changing the scope.
One last point: if you move around in the stack frames (left panel),
Evaluate Expression
will be driven by different scope. Thus if you
want to "poke around" inside some code that called the line at the
breakpoint, it's easy.
Split Screen Without Tabs
Get your code and tests side-by-side without resorting to tabs.
As discussed previously, disabling tabs and focusing on the keyboard helps productivity. But without tabs, how can I see two files at once? For example, the code I'm testing and the tests I'm writing?
You can still split screens without tabs. Simply use the Split Vertically
action (no default keybinding so use Find Action
) and you'll get two frames.
Then open your to-be-tested code on the left and test code on the right.
By default, PyCharm visual test runner tool window is at the bottom. This gives a familiar "TDD" (test-driven development) visual orientation: left for code, right for test, bottom for results. (Although on wide monitors, docking the test tool window on the right might make more sense.)
How to move between the left and right "Split Vertically" frames? The
Go To Next Splitter
action (Alt-Tab
Win/Linux/macOS) is a convenient keybinding.
Since these are the two files you are switching between editing, our old friend the
Recent Files
action (Ctrl-E
Win/Linux, Cmd-E
macOS) is a nice, already-memorized
key sequence.
Run Single Test
Speed up testing by focusing on one test.
You're doing test-driven development (TDD) and you're in "the flow". Everything is clicking. Perhaps you want to focus on just one test:
-
Your tests take a while to run and you don't want the slowdown of running them all
-
Some of your other tests are broken, or your current code breaks them
PyCharm makes it easy to select just one test to run. In fact, there are several ways to do it:
-
With the cursor anywhere in the test you want to focus on, right-click and choose to run that in the test runner
-
Right-click on the test in the test tool listing and choose to run it
The definition of "one test" is also flexible: one test function/method, an entire test class, an entire test file, or a directory. All can be right-clicked to focus on those tests.
What happens when you run one test? PyCharm creates a temporary run configuration, focused on just that test. This run configuration is based off the template run configurations, so if you want to put an environment variable on all your pytest single-tests configs, edit the pytest run configuration template.
Auto-Run Tests
Get into testing mode by telling PyCharm to automatically re-run tests as you type.
TDD, or test-driven development, means "always be testing." In fact, the best way to do this is to put your tests on autopilot.
Some test frameworks have a mode to "watch" your tests and code, detect changes, and re-run tests. But PyCharm makes this even easier, with a button and action.
Simply click the Toggle auto-run
in the test tool window, then run your tests
once. From that point, any time "things change", PyCharm will re-run whatever
tests are currently in that test tool window tab.
It's a very convenient workflow. In fact, since the IDE automatically saves files, you don't even have to perform a save to trigger your test re-runs.
Sometimes you find yourself racing against the IDE: "Keep typing fast before the IDE re-runs the tests!" The test tool window has options where you can adjust the delay, which defaults to 2 seconds. If your tests run fast and you want more immediate feedback, decrease the delay.
This auto-run tests feature combines nicely with other "visual testing" features to help you focus and work productively. Run just one test, or just one file of tests, and turn on the auto-run. Hide passing tests or re-run failing tests, etc.
One last point: this button toggle affects the current test tool window tab only. You might have pinned a run configuration tool window to be "sticky". When you run some other subset of tests, you'll get a tab, but the first is still there and still in auto-run. If tests fail, you will get a notification.
Spot Coverage Gaps Using the Gutter
Let the IDE help you spot coverage gaps in your testing.
Note: Code coverage is a PyCharm Professional feature.
Writing tests for your code is good, but how do you know when you've done enough testing? "Code coverage", via the coverage package, combines your tests and the execution of your code to see and report what spots get hit.
PyCharm makes this easy to set up. You just run the Run with Coverage
action,
for example by clicking the button in the toolbar, and PyCharm runs your tests
with the bundled coverage.py
(or you can use a coverage
that is installed
in your project interpreter.)
Once coverage runs, you'll get a tool window showing a filesystem-like view of your project with statistics at each level.
But better yet, and the subject of this tip, your editor's gutter will be color-coded with coverage information: green for covered and red for not covered. If you checked the preference for "branch coverage", the gutter decorations will include branches in your code.
Those gutter decorations are not just visual: click a line in the gutter to get a popup with some statistics.
Use Local History to Avoid Disaster
Use the IDE's built-in history facility to recover changes when VCS can't help you.
You’re in your repo. You add a file. Later, you make some edits, but then -- you change your mind. You want to revert but you never committed.
Use the IDE’s local history on a file… when you aren’t under version control, or you’re in between commits. Browse each IDE change, see diffs, recover from mistakes.
Delete a file by accident? Go to the folder’s local history, and recover that too!
The Problem
This is the "Oh my goodness you saved my sanity" tip.
Sometimes you are in a project that isn't yet under version control. Or, you've done a lot of work since your last commit. For example, a file is under version control, but you've been very busy.
You pause for a bit, have some inspiration, and hack away. You delete a paragraph, then ultimately finish the text. But now you want that paragraph back! Git can’t help, because you didn't commit before hacking away.
You could try “Undo-Undo-Undo-Copy-Redo-Redo-Paste.” But that’s barbaric. There has to be a better way.
The Solution
This is going be one of those things that people love about our IDEs.
Local History to the rescue. Our IDEs have a built-in facility that tracks revisions for all IDE-initiated changes -- whether you are using a VCS or not.
Right-click on a file and choose “Local History” then “Show History”. On the left, you get a list of changes detected by the IDE. When you select one, you get a diff – comparing to the current file contents – on the right.
As you go through the changes, you see each diff. Like our normal diff viewer, you can apply changes to recover portions.
Perhaps you want the entirety of the file at that point in the history. Right-click on that revision and choose revert.
If a certain revision is known to be in a certain state, right-click and apply a friendly label.
That covers changes to a file. But what if you deleted the file, and it wasn't under VCS? Go to that file’s folder and choose Local History. The deletion event is there, and you can restore the file.
As a wrapup, let’s see the same sequence -- without the mouse!
First, invoke Search Everywhere
and search for the Show Local History
action.
In the Local History window, tab into the Old Changes
panel.
Cursor down to the edit.
Tab to go into the changes. And – on Mac – Ctrl-Cmd-Right arrow
to accept changes.
Create a Project from GitHub
Let PyCharm do the work to clone and setup a project hosted on GitHub.
We all consume a lot of code. Alas, it's a number of steps to get all that code from GH, into a directory, and opened in the IDE.
Let the IDE help out. If you have your GitHub credentials in your preferences, a few easy steps in the IDE will get you going.
First, in the PyCharm menu, choose VCS | Checkout from Version Control | Git
.
You can also skip the keyboard by invoking Find Action
and speed searching for
ch ve
.
This brings up the Clone Repository
dialog. In the URL field, speed search
some letters in the repo name. The IDE looks across all the organizations that
you are in, your personal account, and repos that you're a collaborator for.
If the repo you want isn't on GitHub, paste a URL in here.
In the directory field, supply the path and name of the directory this should clone into.
After answering the dialogs to get the repo and open in a window, your project is ready.
Put New Project Under Version Control
The fastest way to register a new project directory under local version control.
You have a new project, or opened a project not under version control. First thing is to fix that by making a local repository.
You can use your mouse to go to the VCS -> Enable Version Control Integration
menu item. But you can also do this from the keyboard, to get to the same
dialog, without leaving the keyboard.
Use Find Action
(Shift-Ctrl-A
Win/Linux, Shift-Cmd-A
macOS) and speed
search for en ve co
(meaning, Enable Version Control
). It should be the
first matching item. Press Enter
to invoke it.
The dialog that pops up wants a selection of which VCS system to use. If it
is Git, type g
and the dropdown will select Git. Select Ok
to perform
the operation.
This action adds a VCS root in your
Settings/Preferences -> Version Control
preference. Later, when you want
a remote, you can use, for example, Share Project on GitHub
.
Edit Commit Message
Edit the wording in your last commit message, after you committed.
That last commit message…(sigh)...had a typo. You haven’t pushed yet. Just right-click on the commit, choose “Edit Commit Message”, and fix the mistake.
Now your commit history…passes the spell-checker.
The Problem
This is my development life. I finally wrap up a big pile of work, go to do a commit. And, in the rush of victory, make a spelling error, which I spot just as I finish clicking “Commit”. Alas, it’s there, in the history.
We haven’t pushed. So there’s hope.
The Solution
Of course, the best solution is to fix the problem before committing. Our IDEs have a plugin called Grazie which does...let’s just call it “super cool spelling and grammar checking.” It probably warned you about the typo.
It will probably even fix the typo for you.
Back to our messed-up commit message. We could of course, go to the Terminal and type some arcane commit message. And of course, hope we don’t corrupt our repo. This has some downsides: go to the command-line, type something a little obscure, possibly get something wrong, and get no help from the spell checker.
Fortunately, this is the kind of thing our IDEs are great at. Right-click on the commit, and you’ll get a list of actions to take on that commit.
There are LOTS of things we can do to help, as this list shows.
Beside Edit Commit Message
, you can see F2
.
This shows we could have skipped the context menu by selecting the commit and pressing F2
.
We’ll select that option and be prompted with a dialog to edit the commit. The existing commit message is there. We can see, there’s a warning about the typo. We mouseover for more detail. This is the Grazie plugin helping us again.
We can type to fix it, or use Alt-Enter to get a correction.
Once fixed, click Ok to finish the operation. You now see the commit history with the fixed commit message.
One point in closing...we mentioned that you should only use this option if you haven’t pushed. If you go back to older commits and right-click, you’ll see some options are grayed out.
Undo Last Commit
Undo a commit...without misery.
First go to the Git tool window and make sure you’re on the log tab.
It shows the list of commits on the current branch. The most recent one is at the top.
Right-click that commit and in the pop-up window, choose Undo Commit.
That commit has some changes. Let’s keep them in the default changelist. Now the commit tool window says I have changes.
And now that commit…never happened. Let’s look a little deeper.
The Problem
You are editing, say a Markdown file. Let’s leave the Commit tool window and Git tool window open, to see the updates as we go.
You change the title, and make a commit. And for the thousandth consecutive time, you spot a typo, just as the onkeyup event fires when clicking commit. Alas, the commit tool window shows that there are no changes. And, in your Git log, there it is, the mistaken commit.
That means it’s too late, right! Nope, if you haven’t pushed to a “protected” branch, you can clean things up locally. And the IDE puts a convenient UI atop the underlying Git command.
The Solution
In the Git tool window, find the most recent commit. It’s the one at the top. When we select it, we get more detail about the commit. We can double-click the file to see a diff of the change.
When you right-click on a commit, you get some actions you can take on it. Some might be grayed-out. For example, if we right-click on an older, pushed commit, we’ll see “Undo Commit” is grayed-out.
Back to the first commit. Right-click on it, and select “Undo Commit”.
Now, the commit had some changes in them, and these changes need to go somewhere.
The IDE’s changelists provide such a place.
We’ll stick with the Default Changelist
.
This results in our Commit tool window showing the changes when we click ok.
A look in the Git log also shows a change.
That commit is…gone! We’re back to where we were before the commit.
What would this have been like from the command line? Let’s take a look at the Git tool’s Console tab, to see behind the scenes. There it is, the command that we would have had to type, from the command line.
Only Commit Some Changes
Unselect files or changed regions within files during the commit process.
You’ve done a lot of work, but not all the changes should go in one commit. Let’s use partial commit.
In the commit window, look at your changes. Skip the first file by clicking the checkbox. In the second file, open the diff and deselect some of its changes.
Now when you commit -- just those parts are included. The unselected parts remain as changes.
The Problem
You sit down to do some work. It’s going well. You’re in the zone. You have an idea for some other work, something for next week. Exciting stuff, you can’t help yourself. You write it down.
You get a phone call: you forgot a change in something that you did last week. Need to make a small fix.
Back to what you were doing at first. You wrap it up.
Time to ship it, with a good commit message. But there are actually 3 units of work slotted for this commit.
Today’s work, next week’s work, and last week’s work.
Each should get separate commits. Of course, you could just do a single commit, with a commit message for each unit. Fast for you, for now. But not fast for others, trying to decipher the commit history later.
You could roll back the second two changes, then manually re-apply them. But that’s -- how shall we say -- inefficient. You could use the under-appreciated changelist (or stash) facilities.
Maybe there’s a quick and easy solution.
The Solution
What’s a partial commit? Here’s a website that explains it.
That paragraph describes exactly what we want to do. The how? Maybe a little cumbersome. Fortunately our IDEs have been putting a pretty face on this operation for a while.
Let’s return to the commit tool window and walk through committing just the work we want. First, leaving out an entire file. Just click the checkbox on any files.
Sometimes you have a big directory hierarchy of files that might have been copied in. Leaving them out is easy. Just deselect the parent.You could even go in and re-select just a couple.
Next, leaving out part of a file. Bring up the diff tool. Find the change you want to omit and click the checkbox.
If you change your mind, re-select it. This is just like the normal diff tool. You could scroll through changes in a file, between files, use the keyboard-only -- all those productivity tips apply.
When you finish, you’ll see the checkbox has a “dash”. That means it is between “checked” and “unchecked”. Think of it as “some.” You do your commit as normal. It leaves the unselected changes out of the commit, meaning they are still there.
You could continue your process to select the changes for next week’s commit, with a good commit message. Then, the changes for last week’s commit, again with a good commit message. There, you’ve processed all the changes and your commit history is easy to digest later.
Want to see what happened behind the scenes? The Git tool’s Log tab shows the commands issued. This is what you would have had to type.
Run npm Scripts from package.json
Browse your package.json scripts and run in a dedicated tool window.
Modern web development means NodeJS tools which mean a package.json
file.
This file sometimes has helper scripts under the scripts
key. Running
these perform various project operations such as build
.
PyCharm Professional makes it easy to browse and run these. There are
several different paths to opening the npm
tool window:
-
Right-click on
package.json
and chooseShow npm scripts
-
Click the
npm
tool window on left -
Cmd-E npm
Note: If you leave the tool window open, resize it to take less vertical space.
Now that you can see the npm
scripts, double-click on one to run that
npm script in a run window at the bottom. Behind the scenes, this creates
a temporary run configuration of type npm
.
Sometimes your package.json
changes and there's a new/changed/deleted npm
script. The npm
tool window has a Reload scripts
button in its mini-toolbar.
One surprising addition: the names of your npm
scripts are available as
findable actions. If you have a build
script and do Find Action
, speed
searching for run build
will let you immediately invoke it.
Wrap Selection With Tag
Use the keyboard to put a wrapper tag around a selection of code.
You're in an HTML file, working on a nice block of markup, and realize your
CSS framework wants a wrapper <div>
. Don't they always? What's another
<div>
, right?
You could use mouse to move to the start, type in <div>
, go to the end,
type in </div>
, and by then you forgot what you were doing.
Instead:
-
Invoke
Surround With
(Shift-Ctrl-A
Win/Linux,Alt-Cmd-T
macOS) -
Hit
T
to chooseSurround with <tag></tag>
in the Live Templates section -
In the prompt, type the name of the tag
If you're a fan of the Emmet system for quickly generating markup, you can also surround with Emmet.
Create SQLite Database Connection By Drag-and-Drop
Drag-and-drop a .sqlite database file onto the Database tool to create a connection.
PyCharm Professional's Database tool, courtesy of DataGrip, is wonderful. It gives you a professional-level, visual way to work with SQL development in a project.
The Database tool needs to create database connection for the project, which not only lets you browse tables, edit rows, and perform queries, but it also injects superpowers into your Python code. Strings in Python that look like SQL get autocomplete, not only on SQL, but on the tables and columns in your project. Even refactoring those names.
But creating a database connection means filling in some details. For
a SQLite database, it's a lot easier. Just drag and drop your
.sqlite
db file onto the Database tool window. Note: You might have
to download the SQLite drivers.
Once done, your project has a database, you can browse the tables, and use the schema in your Python code's SQL strings.