Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#13: More Module Importing Options

                          << Previous Tutorial           Next Tutorial >>
On this page: import x as y, from x import *, import all.

Get Started

Video Summary

  • Script and shell outputs from this tutorial.
  • You can import a module under a different alias, so that you avoid the redundancy of the previous tutorial. For example, typing import time as t will replace the name of the module time with t, so that in future instances you only need to type t for the time module, as in t.time() instead of time.time(). However, be aware when using this feature that the old name for the module will no longer be understood within Python and may lead to errors if used.
  • When importing, you can also choose to import specific functions of a given module, further simplifying the line of code that needs to be typed. For example, typing from time import time will import the basic time() function from the time module, so that the basic print time.time() command can be typed simply as time().
  • Be aware that reduced commands like localtime(time()) and asctime(localtime(time())) will still return errors when used in conjunction with the command from time import time. This is because only the basic time() function has been imported from the time module. To import all of the functions from a given module, use an asterisk *. For example, from time import * will import the time() function as well as localtime() and asctime(), so that the lines above will function properly.
  • Be careful when importing all functions from a given module if there are multiple modules and functions within your code as the vagueness of the import all command can lead to errors as your code becomes more complex.

Learn More

  • In the script, the extra print statements print '' does nothing more than adding an extra empty line. Ed didn't cover the newline character '\n' but we learned it! The script therefore could be re-written like below and produce a similar result. (Why "similar"? Because print will insert an invisible space ' ' before '\n'.)
    print time(), '\n'          # Alternatively: time() + '\n',
                                #  which does not insert extra space ' '
    print localtime(time()), '\n'
    print asctime(localtime(time()))
    foo.py
    

Explore