Autoflake removes unused imports and unused variables as reported by pyflakes. Install it
pip install --upgrade autoflake
Now select a file which you want to clean and run this in terminal
autoflake --in-place --remove-unused-variables example.py
Instead of running this command every time, I wrote a simple elisp function and assigned a F8 key to that function. So while writing the code itself it can clean it & it's much efficient.
Put the above code in your emacs configuration file, restart it & press F8 whenever you want to clean the code.;; Py-rm - Remove unused variables & imports from python
(defun pyrm ()
(interactive)
(setq command (concatenate 'string "autoflake --in-place --remove-unused-variables " buffer-file-name))
(shell-command command)
;; Reload the modified file
(revert-buffer t t)
)
;; set a custom key for pyrm
(global-set-key [f8] 'pyrm)
However, if you just need to highlight but not delete them, you can install flymake and then enter this.
M-x flymake-mode RET
Screenshots:
Simple Python Code
Highlighted with flymake-mode