python list

How to Write Modules in Python3?

Introduction

Python modules are also another python files .py files that consist of Python code. Most of the modules are available at the Python Standard Library and they are installed during the python standard installation. Other packages can be installed via pip. We can also create custom modules which are as per our requirements. Even they are comprised of additional python .py files.

This is a simple tutorial which guides you through writing your very first Python module.

Writing and Importing Modules

Here we will create a python file firstmodule.py where we will define three basic methods print, add and multiply. After creating the file, we will show how it will be imported as a module.

Below is a code snipped of a file firstmodule.py

# firstmodule.py
def hello():
	print("This is first method.")


def addition():
	print(2+2)


def multiply():
	print(8*7)

If we simply run the program as python firstmodule.py the code would execute easily but we won’t be able to see any output at this moment. To import this file as a module we can now do the following in our python interpreted:

>>> import firstmodule
>>> firstmodule.hello()
This is first method.
>> from firstmodule import addition
>>> addition()
4
>>> from firstmodule import *
>>> multiply()
56
>>> hello()
This is first method.

In the above code we demonstrated how we can import the module we created and get the result defined within the methods exposed.

Packaging the Modules

Now that we have created a simple module firstmodule, in this section we will bundle the module inside a Package. Package is simply a directory which lists all the modules we have created in our project.

Before packaging the modules, create a new module modulenext such that you will get an idea of bundling multiple modules in a package. Follow the same process as mentioned in the above section to create new module modulenext. For the test purpose create same methods copy file and only rename firstmodule.py to modulenext.py

Now create a directory named as mypackage. Add the modules you created inside mypackage. Next create a new initializer file __init__.py. Your folder structure should now look like this:

├──mypackage
   ├── helloworld.py
   ├── __init__.py
   ├── nextworld.py

The init.py files are required to make Python treat the directories as containing packages.. This is now your new package which has two modules which you just created. The