'Example of " remove unused imports" can have bad side effects in python?

I'm looking for an example of how removing unused imports can lead to breaking otherwise valid programs. My question was inspired looking at this issue: https://github.com/psf/black/issues/86

Could someone please point me to an example?



Solution 1:[1]

When you import a module in Python, you execute all the code in that file (and all of its imports).

By convention only this code is side-effectless and usually just provides classes and such, but there's no real reason this has to be true. A poorly written module could perform necessary steps to function correctly as part of the code triggered during import.

For example it's entirely possible to have code like:

# my_db/init.py
    from my_db.core import MyDB

    MyDB.do_very_important_setup()


# my_db/other.py
    import my_db.init
    from my_db.core import MyDB

    MyDB.do_some_work_assuming_setup_has_occurred()

Is this horrible? Yes. Should you do it? No.

Can you guarantee nobody else has?

Solution 2:[2]

When a module first gets imported, all the code within that module is run. Convention and good practice dictates that the module shouldn't make any changes to the rest of the environment, but this isn't always the case (for example, a module could change a couple of variables in sys for the entire program, when it's first imported).

It is possible that someone could import such a module purely for its side effects, and then never explicitly refer to it in the rest of their code. A linting/formatting tool like black would then detect it as unused, and remove it, and suddenly the side-effects it was having are no longer in effect, and the program breaks as a result.

I can't come up with any specific examples at this time, but I know I've seen at least one before, and I was personally working on such a module until I realized it was a poor idea and stopped.

Solution 3:[3]

Consider you have following structure:

- root
   |--folder1
         |-- __init__.py
         |-- server.py
   |--main.py

And following content:

# main.py
import folder1 as f
print("I am doing stuff but don't need f")


# __init__.py
from folder1 import server


#  server.py
# Start a server, or do something else you need

When you remove the folder1 import in main.py it would stop doing the thins in __init__.py and server.py. I would definetly consider that as bad code, but it is possible.

Solution 4:[4]

I don't know if this answers your question, but if you remove the unused import, the first 2 icons are not displayed anymore.

https://github.com/theonlycodingbear/unused-imports-problem.git

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Scarabee
Solution 2 Green Cloak Guy
Solution 3
Solution 4 FelixTheCat