What's the difference between importing a whole module vs importing just the required method from the module in python?

789 views Asked by At

When using scikit learn or other similar Python libraries, what's the difference between doing:

import sklearn.cluster as sk
model = sk.KMeans(n_clusters=n)

And

from sklearn.cluster import KMeans 
model = KMeans(n_clusters=n)

Is there any advantage to using one way over the other?

1

There are 1 answers

2
2rs2ts On

Well, in your first example, you've made the module sklearn.cluster accessible as sk and you can refer to its members accordingly. In your second example, you've only imported one member of sklearn.cluster, KMeans, so only that one is accessible. That's the difference.

As for advantages? Do whichever makes your code easier to read.