Technology Training

Implementing Python Modules As Scripts

I will quickly show you how to implement modules in python as scripts.

PH

Perete Harrison

Engineering, Atop Web Technologies

2 min read
Implementing Python Modules As Scripts

I will quickly show you how to implement modules in python as scripts.

What are modules in python?

Let says you are building a complex web application, consisting of user registrations, user login, and commenting system. It’ will be easier to split the user registrations, a user login, and commenting system into several files for easier maintenance. Moreover, you may also want to use the user login codes which you’ve already written in different sections or programs without copying its codes into the section or programs. The way python makes this happen is by putting the user login codes into a file called a module.

A module is a python file containing codes you want to include in your program. As per the definition from python documentation “A module is a file containing Python definitions and statements.” The file name is the module name with a .py.

File name user.py

1# User login Module
2
3def login():
4print("Login in progress..")

Either in a python interpreter or in a different file, you can import this module with the following command.

1import user
2user.login()
3
4OutPut:
5Login in progress..


Implementing or Executing modules as scripts

We now understand the basic implementation of a python module.

To run the user login module as a script, change the module codes as below.

File name user.py

1# User login Module
2
3def login():
4 print('Login in progress..Wrap Up!')
5
6if __name__ == "__main__":
7 login()

What’s in a (Python’s) __name__?

__name__ is a special global variable that contains the module name as “string” when you import the module. When you run the module as a script its values must be set to __main__

__main__ is the entry point to our program or better known as “top-level code environment”

1python user.py
2
3OutPut:
4Login in progress..

Wrap Up!

This is a simple demonstration of what the python module entails. For a deep dive consider taking a look at the Python documentation.

Posted in

Technology Training

Related stories