Skip to content

Use of implicitly imported module namespace not considered correctly #180

@cb109

Description

@cb109

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!

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingchangelogChanges should be written to the changelog file.

Projects

Status

📋 Backlog

Relationships

None yet

Development

No branches or pull requests

Issue actions