Why does from scipy import spatial work, while scipy.spatial doesn't work after import scipy?

前端 未结 3 435
野趣味
野趣味 2020-12-11 14:41

I would like to use scipy.spatial.distance.cosine in my code. I can import the spatial submodule if I do something like import scipy.spatial<

相关标签:
3条回答
  • 2020-12-11 15:16

    That's because scipy is a package, not a module. When you import a package, you don't actually load the modules inside, and thus package.module causes an error.

    However, import package.module would work, because it loads the module, not the package.

    This is the standard behavior for most import statements, but there are a few exceptions.

    Here is the same case for urllib in Python 3:

    >>> import urllib
    >>> dir(urllib)
    ['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '__path__', 'error', 'parse', 'request', 'response']
    

    See? there is no submodules there. To access its submodule, we ask for the submodule:

    >>> import urllib.request
    >>> 
    

    Hope this simple explanation helps!

    0 讨论(0)
  • 2020-12-11 15:25

    Use scipy version 1.2.1 to solve this issue......

    0 讨论(0)
  • 2020-12-11 15:30

    Importing a package does not import submodule automatically. You need to import submodule explicitly.

    For example, import xml does not import the submodule xml.dom

    >>> import xml
    >>> xml.dom
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'dom'
    >>> import xml.dom
    >>> xml.dom
    <module 'xml.dom' from 'C:\Python27\lib\xml\dom\__init__.pyc'>
    

    There's an exception like os.path. (os module itself import the submodule into its namespace)

    >>> import os
    >>> os.path
    <module 'ntpath' from 'C:\Python27\lib\ntpath.pyc'>
    
    0 讨论(0)
提交回复
热议问题