Tutorial :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.


Don't do from spam import *.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »