Ofer Sadan
Ofer Sadan

Reputation: 11932

Ignoring "Unused import statement" in just one file (PyCharm)

I have a project where multiple files are importing from common.py file because they all use the same modules / packages and I wanted uniformity and it's easier to change values or packages in just one place.

common.py looks like this (only much longer):

import json
import os
import sys
from datetime import datetime
from pathlib import Path
from pprint import pprint
from time import sleep

import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from pdir.api import PrettyDir

# AND MUCH MORE... with other common functions and classes

And all other files in the project start with:

from common import *

Everything works fine. But because some of the imports aren't used in common.py itself, PyCharm fails to see that they are used in other modules, and marks them as "Unused import statement".

I don't want to silence the inspection for the entire project because it is quite useful in other places. Is there any way to force PyCharm to check if the import is used elsewhere in the project, or alternatively just silence the inspection for only this file?

Upvotes: 2

Views: 2740

Answers (2)

Ofer Sadan
Ofer Sadan

Reputation: 11932

Ended up solving it myself, so leaving the steps here for anyone else to find:

  1. File | Settings | Appearance and Behavior | Scopes | + (to add a new one) | Local
  2. Named this scope # noinspection PyUnresolvedReferences So I'll always remember what it's used for
  3. Select only the relevant file in the folder view and click on "Include" and confirm
  4. File | Settings | Editor | Inspections
  5. In the list of inspections, click on "Unresolved references" under the "Python" category. On the right there's a box that says this is used "In All Scopes" - click on it and select our new scope (in this case, named # noinspection PyUnresolvedReferences).
  6. Now the box shows 2 lines, the first is our new scope that needs to be unchecked (or the severity can change if you'd like to do that). The second line is "Everywhere Else" and it should be checked so the warning will stay elsewhere in the project.

I'm not accepting my own answer at the moment because I still hope there is a simpler way to accomplish this

Upvotes: 5

deceze
deceze

Reputation: 522155

Two options:

  1. Suppress the inspection by preceding it with the comment # noinspection PyUnresolvedReferences (this is offered as an option in the action dialog). Unfortunately that only applies to a line or block at a time, not the entire file. So you'd either have to annotate each line, or put all import statements in some sort of block (e.g. a function) just for this purpose.

  2. Add an __all__ = ('json', ...) line to the file to explicitly annotate those symbols for export; unfortunately you'll have to do that for each imported item.

Upvotes: 2

Related Questions