「sound.effects パッケージがインポートされていることのみを確認します」とはどういう意味ですか?
モジュールのインポートとは、ファイル内の最上位インデント レベルですべてのステートメントを実行することを意味します。これらのステートメントのほとんどは、関数またはクラスを作成して名前を付ける def または class ステートメントになります。ただし、他のステートメントがある場合は、それらも実行されます。
james@Brindle:/tmp$ cat sound/effects/utils.py
mystring = "hello world"
def myfunc():
print mystring
myfunc()
james@Brindle:/tmp$ python
Python 2.7.5 (default, Jun 14 2013, 22:12:26)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sound.effects.utils
hello world
>>> dir(sound.effects.utils)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'myfunc', 'mystring']
>>>
この例では、モジュール sound.effects.utils をインポートすると、モジュール内に「mystring」と「myfunc」という名前が定義され、ファイルの最後の行で「myfunc」の呼び出しも定義されていることがわかります。
「sound.effects パッケージをインポートする」とは、「sound/effects/init.py という名前のファイル内のモジュールをインポート (つまり、実行) する」ことを意味します。
説明が言うと
そして、パッケージで定義されている名前をインポートします
それは(紛らわしいことに)「インポート」という言葉に別の意味を使用しています。この場合、パッケージで定義された名前 (つまり、init .py で定義された名前) がパッケージの名前空間にコピーされることを意味します。
sounds/effects/utils.py
以前の名前を に変更するとsounds/effects/__init__.py
、次のようになります。
>>> import sound.effects
hello world
>>> dir(sound.effects)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'myfunc', 'mystring']
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'sound': <module 'sound' from 'sound/__init__.pyc'>, '__doc__': None, '__package__': None}
前と同じようにmyfunc
とmystring
が作成され、sounds.effects
名前空間に含まれるようになりました。
このfrom x import y
構文は、独自の名前空間ではなくローカル名前空間に物をロードするため、これらの名前に切り替えると、import sound.effects
代わりfrom sound.effects import *
にローカル名前空間にロードされます。
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> from sound.effects import *
hello world
>>> locals()
{'myfunc': <function myfunc at 0x109eb29b0>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'mystring': 'hello world', '__name__': '__main__', '__doc__': None}
>>>