Pythonのfrom importとimportの使い方

3227 ワード

ソース:https://docs.python.org/3/tutorial/modules.html#packages
  • Users of the package can import individual modules from the package, for example:
  • #  sound.effects   echo  
    import sound.effects.echo
    

    This loads the submodule sound.effects.echo. It must be referenced with its full name.
    sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
    
  • An alternative way of importing the submodule is:
  • #  sound.effects   echo  
    from sound.effects import echo
    

    This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:
    echo.echofilter(input, output, delay=0.7, atten=4)
    
  • Yet another variation is to import the desired function or variable directly:
  • #  sound.effects.echo    echofilter  
    from sound.effects.echo import echofilter
    

    Again, this loads the submodule echo, but this makes its function echofilter() directly available:
    echofilter(input, output, delay=0.7, atten=4)
    

    Note that when using from package import item , the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.
    Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.
    別のソース:https://stackoverflow.com/questions/710551/use-import-module-or-from-module-import

  • import package
    import module
    

    With import , the token must be a module (a file containing Python commands) or a package (a folder in the sys.path containing a file __init__.py .)
  • When there are subpackages:
  • import package1.package2.package
    import package1.package2.module
    

    the requirements for folder (package) or file (module) are the same, but the folder or file must be inside package2 which must be inside package1, and both package1 and package2 must contain init.py files. https://docs.python.org/2/tutorial/modules.html
  • With the from style of import:
  • from package1.package2 import package
    from package1.package2 import module
    

    the package or module enters the namespace of the file containing the import statement as module (or package) instead of package1.package2.module. You can always bind to a more convenient name:
    a = big_package_name.subpackage.even_longer_subpackage_name.function
    
  • Only the from style of import permits you to name a particular function or variable:
  • from package3.module import some_function
    

    is allowed, but
    import package3.module.some_function 
    

    is not allowed.