import subprocess, types
def scrape_wildcard(filename, modvars):
"Get variables imported from module in wild * import"
error = "W0614: Unused import "
unused = []
for line in quickrun(['pylint', filename]):
if error in line:
unused.append(line.split(error)[1].split()[0])
out = dict()
for name in set(modvars.keys()) - set(unused):
if not name.startswith('__'):
func = modvars[name]
if not isinstance(func, types.ModuleType):
out[name] = modvars[name]
return out
def quickrun(cmd, check = False, encoding = 'utf-8', errors = 'replace'):
ret = subprocess.run(cmd, stdout = subprocess.PIPE, check = check)
return ret.stdout.decode(encoding = encoding, errors = errors).splitlines()
import ?? ?? ? as mymod
filename = "?????"
print('from', mymod.__name__, 'import', ', '.join(scrape_wildcard(filename, vars(mymod)).keys()))
''
'
This warning occurs in conjunction with issue F403, 'from module import *' used. It means that the variable name could be undefined, but flake8 cannot be sure because it also could also be imported in the star imports.,Confirm that the variable is defined in the star imports. If it is, explicitly import it instead of importing *. If not, then define the variable.,Descriptions and examples for each of the rules in Flake8 (pyflakes, pycodestyle, and mccabe).
from mymodule
import *
def print_name():
print(name) # name could be defined in mymodule
from mymodule
import name
def print_name():
print(name)
from mymodule
import *
def print_name(name):
print(name)
Tool to automatically fix some issues reported by flake8 (forked from autoflake). , Tool to automatically fix some issues reported by flake8 (forked from autoflake). ,Additionally, autoflake8 also supports load from stdin and printing to stdout, which makes it very easy for users to integrate with their custom editors.,In terms of future plans, we also plan to eventually stop using regular expressions and rely on actual AST rewriting to fix issues reported by flake8.
$ autoflake8--in - place--remove - unused - variables example.py
import math
import re
import os
import random
import multiprocessing
import grp, pwd, platform
import subprocess, sys
def foo():
from abc
import ABCMeta, WeakSet
try:
import multiprocessing
print(multiprocessing.cpu_count())
except ImportError as exception:
print(sys.version)
return math.pi
import math
import sys
def foo():
try:
import multiprocessing
print(multiprocessing.cpu_count())
except ImportError:
print(sys.version)
return math.pi
$ pip install--upgrade autoflake8
-repo: https: //github.com/fsouza/autoflake8
rev: v0 .4 .0
hooks:
-id: autoflake8
usage: autoflake8[-h][-c][-r][--exclude globs][--expand - star - imports][--remove - duplicate - keys][--remove - unused - variables][--version][-v][--exit - zero - even - if -changed ][-i | -s] files[files...] positional arguments: files files to format optional arguments: -h, --help show this help message and exit - c, --check return error code if changes are needed - r, --recursive drill down directories recursively --exclude globs exclude file / directory names that match these comma - separated globs --expand - star - imports expand wildcard star imports with undefined names; this only triggers if there is only one star import in the file; this is skipped if there are any uses of `__all__` or `del` in the file --remove - duplicate - keys remove all duplicate keys in objects --remove - unused - variables remove unused variables --keep - pass - statements keep all `pass` statements --keep - pass - after - docstring keep `pass` statements after a newline ending on "" " --version show program 's version number and exit - v, --verbose print more verbose logs(you can repeat `-v` to make it more verbose) --exit - zero - even - if - changed - i, --in - place make changes to files instead of printing diffs - s, --stdout print changed text to stdout.defaults to true when formatting stdin, or to false otherwise
Assumes only names in the current file are used by star imports (e.g., it won’t work to replace star imports in __init__.py).,removestar does not replace star import lines that are marked with Flake8 noqa comments that permit star imports (F401 or F403).,If there are multiple import * statements, it may not be clear which names come from which module. In some cases, both modules may have a given name, but only the second import will end up being used. This can break people’s intuition that the order of imports in a Python file generally does not matter.,Here are some official Python references stating not to use import * in files:
pip install removestar
conda install - c conda - forge removestar
$ removestar file.py # Shows diff but does not edit file.py $ removestar - i file.py # Edits file.py in -place $ removestar - i module / # Modifies every Python file in module / recursively
mymod / | __init__.py | a.py | b.py
# mymod / a.py
from.b
import *
def func(x):
return x + y
# mymod / b.py x = 1 y = 2