Problem
An import like import module.submodule is removed when module.submodule is not used 1:1. However, we may use module.other_submodule or module.some_other_name in the file, which then becomes invalid and as such our codebase is broken.
Example
# my_module.py
import urllib.request
def parse_url(url):
return urllib.parse.urlparse(url)
print(parse_url("http://google.com"))
The urllib.parse.urlparse(url) works here (somewhat surprisingly), because import urllib.request implicitly imports urllib, allowing us to access urllib.parse as well.
Running unimport against the file will detect import urllib.request as unused and remove it:
$ unimport my_module.py --remove
diff --git a/my_module.py b/my_module.py
-import urllib.request
def parse_url(url):
As a result, the module is now broken:
$ python my_module.py
Traceback (most recent call last):
File "my_module.py", line 7, in <module>
print(parse_url("http://google.com"))
File "my_module.py", line 4, in parse_url
return urllib.parse.urlparse(url)
NameError: name 'urllib' is not defined
Proposed Solution
unimport should be able to detect these cases and either prefer to not remove anything here or at least let us configure the behaviour to be more or less forgiving (maybe via --strict defaulting to True). I do see unimport as a cleanup mechanism to keep the codebase tidy, but it should never break anything, I'd much prefer to have a weird import lingering around if I had to choose.
Thank you for your time!
Problem
An import like
import module.submoduleis removed whenmodule.submoduleis not used 1:1. However, we may usemodule.other_submoduleormodule.some_other_namein the file, which then becomes invalid and as such our codebase is broken.Example
The
urllib.parse.urlparse(url)works here (somewhat surprisingly), becauseimport urllib.requestimplicitly importsurllib, allowing us to accessurllib.parseas well.Running
unimportagainst the file will detectimport urllib.requestas unused and remove it:As a result, the module is now broken:
Proposed Solution
unimportshould be able to detect these cases and either prefer to not remove anything here or at least let us configure the behaviour to be more or less forgiving (maybe via--strictdefaulting toTrue). I do seeunimportas a cleanup mechanism to keep the codebase tidy, but it should never break anything, I'd much prefer to have a weird import lingering around if I had to choose.Thank you for your time!