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

# User login Module

def login(): 
print("Login in progress..")

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

import user
user.login()

OutPut:
Login 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

# User login Module

def login():
  print('Login in progress..Wrap Up!')

if __name__ == "__main__":
  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”

python user.py

OutPut:
Login 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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Isaac
Isaac
2 years ago

Itís difficult to find educated people about this subject, but you sound like you know what youíre talking about! Thanks

Mark
Mark
2 years ago

Thanks for your blog, nice to read. Do not stop.