Search code examples
pythonimportmodule

different import syntaxes in python


Here are three similar import statements that I am trying in Spyder:

from sklearn.datasets import load_iris

This code works perfectly well. When I try:

from sklearn import datasets.load_iris

This gives "Invalid Syntax" error. When I try:

from sklearn import datasets
from datasets import load_iris

It says "No module named datasets" error. When I try:

import sklearn.datasets
from datasets import load_iris

It gives the same error "No module named datasets".

Aren't all these statements same and equivalent?? Why only one of them works? Please clarity.


Solution

  • Here's a more elaborated answer to your question: `from ... import` vs `import .`

    TL;DR

    Python expects a module, or package path, when using import ....

    For from ... import ... statements, the from ... part, works the same way as import ..., and expects a package or module path. The ... import ... section allows you to import any object found within the submodule you've specified at from .... It does not allow, however, to access specific namespaces from a given object (e.g.: datasets.load_iris)

    Here is all the ways you import the function load_iris from your examples:

    from sklearn.datasets import load_iris
    load_iris()
    
    # OR
    
    import sklearn.datasets
    
    # Create a namespace for sklearn.datasets.load_iris
    load_iris = sklearn.datasets.load_iris
    load_iris()
    
    # OR
    
    import sklearn.datasets
    
    # Use it directly
    sklearn.datasets.load_iris()
    
    # OR
    
    import sklearn.datasets as datasets
    
    # Create a namespace for sklearn.datasets.load_iris
    load_iris = datasets.load_iris
    load_iris()
    
    # OR
    
    import sklearn.datasets as datasets
    
    # Use it directly
    datasets.load_iris()
    

    Regarding your last example:

    
    import sklearn.datasets
    from datasets import load_iris
    
    
    # CORRECT USE
    
    import sklearn.datasets
    from sklearn.datasets import load_iris
    

    You have imported sklearn.datasets, AS sklearn.datasets. To access the datasets module you imported, you need to specify the name you used during import.