Sep. 18, 2012

Modules

This is a new series of articles here at Python for beginners, that are supposed to be a starting point for completely beginners of Python. See it as a cheat sheet, reference, manual or whatever you want. The purpose is to very short write down the basics of Python. This page will describe how to use Modules in Python.

Python Modules

Python modules makes the programming a lot easier. It’s basically a file that consist of already written code. When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is. There are different ways to import a module. This is also why Python comes with battery included

Importing Modules

Let's how the different ways to import a module

import sys    		
#access module, after this you can use sys.name to refer to things defined in module sys.

from sys import stdout  
# access module without qualiying name. 
This reads from the module "sys" import "stdout", so that we would be able to 
refer "stdout"in our program.

from sys import *       
# access all functions/classes in the sys module. 

Catching Errors

I like to use the import statement to ensure that all modules can be loaded on the system. The Import Error basically means that you cannot use this module, and that you should look at the traceback to find out why.

Import sys
try:
    import BeautifulSoup
except ImportError:
    print 'Import not installed'
    sys.exit()

Python Standard Library

URL: http://docs.python.org/library/index.html Collection of of modules that are already on the system, there is no need to install them. Just import the modules you want to use. Search for a module: http://docs.python.org/py-modindex.html

Python Package Index

URL: http://pypi.python.org/pypi Created by community members. It's a repository of software containing more than 2400 packages

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.