Unresolved references

Another common problem that PyCharm's code analyzer can detect—and this one is actually an error—is unresolved references. As we mentioned previously, in our example, we are using the sqrt() function from the math module without importing it. The general error extends to any unimported and undeclared API.

To fix this error, you can manually import the function from the math module by typing the import statement into the code. On the other hand, you can take advantage of intention actions by performing the following steps:

  1. Move your cursor to where the error is, that is, the math part of print(math.sqrt(4)).
  2. A red light-bulb icon will appear shortly at the beginning of the line of code, as shown in the following screenshot. Click on it to open the Intention menu:

Fixing unresolved references in PyCharm
  1. From here, we can choose the appropriate action to take to fix the error. Since we need to import the function from the math module, choose the first option, that is, Import this name. There will be another menu asking you where to import a module named math from (since there are multiple in Python). Choose the first option.
  2. After this, an appropriate import statement will be automatically inserted at the beginning of the file, and the error will go away.

Again, we can imagine the convenience of this feature in large projects, where it is difficult to keep track of all the libraries and packages that the project uses. PyCharm's intention actions nicely handle these nitty-gritty details for us.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset