Creating your own modules is easy, you have been doing it all along! Every Python program is also a module. The following example should make it clear.
Example 8.3. How to create your own module
#!/usr/bin/python # File : mymodule.py def sayhi(): print 'Hi, this is mymodule speaking.' version = '0.1' # End of mymodule.py
The above was a sample 'module'. As you can see, there is nothing special in it compared to our usual Python programs. The following is a Python program that uses this module. Remember that the module should be placed in the same directory as the program or in one of the directories listed in sys.path.
#!/usr/bin/python # File : mymodule_demo.py import mymodule mymodule.sayhi() print mymodule.version
Here is also a version utilising the from..import syntax.
#!/usr/bin/python # File : mymodule_demo2.py from mymodule import * # You can also use: # from mymodule import sayhi, version sayhi() print version
The output of mymodule_demo2.py program is the same as the output of mymodule_demo.py program.