开发者

basic questions about "import"

I have some开发者_开发百科 questions about Python's import statement:

  1. What is the difference between import <module> and from <module> import *?

  2. How can I import a module that is not in the same directory? (and not in PythonHome)

Please consider I am a Python newbie


import imports the module into the global namespace. from import imports the named items into the namespace.

So with a plain import you always have to reference the module:

>>> import datetime
>>> day = datetime.date.today()

But with an from import you can reference the items directly:

>>> from datetime import date
>>> day = date.today()

If you use from somemodule import * it will import everything from the module into your namespace. While this might seem convenient it's best not to do this. It's frowned upon as it's harder to tell which things have come from the module when reading the code and there's a possibility of collisions between names you use and names you have inadvertently imported from the module.

The easiest way to import a module from a different directory is to add that directory to your PYTHONPATH.


  • http://docs.python.org/tutorial/modules.html
  • http://effbot.org/zone/import-confusion.htm
  • How to do relative imports in Python?

Don't do from spam import *.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜