Python Module Import Best Practices: Avoid Importing All Names

Using many names from a #Python module? Import them all: from MODNAME import * Wait: This is usually a TERRIBLE idea! • Potential namespace collisions • Less readable code • Module upgrades affect globals in your program I know, it's tempting — but don't!

  • No alternative text description for this image

That is not a BKM, neither is suggested by standard.

using python 3.8, individual imports summed up were 873, all imports together were 849, so potentially up to 24 global variables/functions were overwritten

  • No alternative text description for this image

Who is tempted to do this??

That isn't a good practice. One way to immediately gauge efferent coupling in a source file (the number of classes this class depends on) is to look at the import statements. That information can be used to determine if the class is doing too much and should be refactored.

How would this be different to Import numpy as np ?

it would be interesting to compare the sum of all "len(globals())" when importing these individually against the 827, to see if some were overwritten/clashing

True, it's better to be precise

See more comments

To view or add a comment, sign in

Explore content categories