Python All-in-One For Dummies
Book image
Explore Book Buy On Amazon
For all the hoopla about Python modules, a module is actually a pretty simple thing. In fact, a Python module is just a file with a .py extension that contains Python code. That’s it. So any time you write Python code and save it in a .py file, you’ve basically created a module.

That’s not to say you always have to use that code as a module. It can certainly be treated as a standalone app. But if you wanted to create your own Python module, with just code that you need often in your own work, you could certainly do so.

programming Python modules ©Shutterstock/dTosh

A Python module is also just a file with a .py filename extension. The name of the module is the same as the filename (without the .py). Like any .py file, the module contains Python code. As a working example, let’s suppose you want to have three functions to simplify formatting dates and currency values. You can make up any name you like for each function. For our working example, we’ll use these three names:

  • to_date(<em>any_str</em>): Lets you pass in any string (any_str) date in mm/dd/yy or mm/dd/yyyy format and sends back a Python datetime.date that you can use for date calculations.
  • mdy(<em>any_date</em>): Lets you pass in any Python date or datetime, and returns a string date formatted in mm/dd/yyyy format for display on the screen.
  • to_curr(<em>any_num, len</em>): Lets you pass in any Python float or integer number and returns a string with a leading dollar sign, commas in thousands places, and two digits for the pennies. The len is an optional number for length. If provided, the return value will be padded on the left with spaces to match the length specified
So here is all the code for that:
# Contains custom functions for dates and currency values.
import datetime as dt
def to_date(any_str):
""" Convert mm/dd/yy or mm/dd/yyyy string to datetime.date, or None if invalid date. """
try:
if len(any_str) == 10:
the_date = dt.datetime.strptime(any_str,'%m/%d/%Y').date()
else:
the_date = dt.datetime.strptime(any_str,'%m/%d/%y').date()
except (ValueError, TypeError):
the_date = None
return the_date
def mdy(any_date):
""" Returns a string date in mm/dd/yyyy format. Pass in Python date or string date in mm/dd/yyyy format """
if type(any_date) == str:
any_date = to_date(anydate)
# Make sure its a dateime being forwarded
if isinstance(any_date,dt.date):
s_date = f"{any_date:'%m/%d/%Y'}"
else:
s_date = "Invalid date"
return s_date
def to_curr(anynum, len=0):
""" Returns a number as a string with $ and commas. Length is optional """
s = "Invalid amount"
try:
x = float(anynum)
except ValueError:
x= None
if isinstance(x,float):
s = '
You can create the same file yourself and name it myfunctions.py if you want to follow along. Notice that the file contains only functions. So if you run it, it won't do anything on the screen because there is no code in there that calls any of those functions.

To use those functions in any Python app or program you write, first make sure you copy that myfunc.py file to the same folder as the rest of the Python code that you’re writing. Then, when you create a new page, you can import myfunc as a module just as you would any other module created by somebody else. Just use

import myfunc
You will have to use the module name in front of any of the functions that you call from that module. So if you want to make the code a little more readable, you can use this instead:
import myfunc as my
With that as your opening line, you can refer to any function in your custom Python module with my. as the prefix. For example, my.to_date() to call the to_date function. Here is a page that imports the module and then tests out all three functions using that my syntax:
# Import all the code from myfunc.py as my.
import myfunc as my
# Need dates in this code
from datetime import datetime as dt
# Some simple test data.
string_date="12/31/2019"
# Convert string date to datetime.date
print(my.to_date(string_date))
today = dt.today()
# Show today's date in mm/dd/yyyy format.
print(my.mdy(today))
dollar_amt=12345.678
# Show this big number in currency format.
print(my.to_curr(dollar_amt))
You can also skip using the prefix if you import items by name. In this case, that means you could call to_date() and mdy() and to_curr() without using the my. prefix. The first line of code would need to be
from myfunc import to_date, mdy, to_curr
The rest of the code would be the same as in the previous example, except you can leave off the my. prefixes as in the following code:
# Import all the code from myfunc.py by name.
from myfunc import to_date, mdy, to_curr
# Need dates in this code
from datetime import datetime as dt
# Some simple test data.
string_date="12/31/2019"
# Convert string date to datetime.date
print(to_date(string_date))
today = dt.today()
# Show today's date in mm/dd/yyyy format.
print(mdy(today))
dollar_amt=12345.678
# Show this big number in currency format.
print(to_curr(dollar_amt))

Check out these 10 amazing Python programming resources for more information.

+ f"{x:,.2f}" if len > 0: s=s.rjust(len) return s
You can create the same file yourself and name it myfunctions.py if you want to follow along. Notice that the file contains only functions. So if you run it, it won't do anything on the screen because there is no code in there that calls any of those functions.

To use those functions in any Python app or program you write, first make sure you copy that myfunc.py file to the same folder as the rest of the Python code that you’re writing. Then, when you create a new page, you can import myfunc as a module just as you would any other module created by somebody else. Just use

import myfunc
You will have to use the module name in front of any of the functions that you call from that module. So if you want to make the code a little more readable, you can use this instead:
import myfunc as my
With that as your opening line, you can refer to any function in your custom Python module with my. as the prefix. For example, my.to_date() to call the to_date function. Here is a page that imports the module and then tests out all three functions using that my syntax:
# Import all the code from myfunc.py as my.
import myfunc as my
# Need dates in this code
from datetime import datetime as dt
# Some simple test data.
string_date="12/31/2019"
# Convert string date to datetime.date
print(my.to_date(string_date))
today = dt.today()
# Show today's date in mm/dd/yyyy format.
print(my.mdy(today))
dollar_amt=12345.678
# Show this big number in currency format.
print(my.to_curr(dollar_amt))
You can also skip using the prefix if you import items by name. In this case, that means you could call to_date() and mdy() and to_curr() without using the my. prefix. The first line of code would need to be
from myfunc import to_date, mdy, to_curr
The rest of the code would be the same as in the previous example, except you can leave off the my. prefixes as in the following code:
# Import all the code from myfunc.py by name.
from myfunc import to_date, mdy, to_curr
# Need dates in this code
from datetime import datetime as dt
# Some simple test data.
string_date="12/31/2019"
# Convert string date to datetime.date
print(to_date(string_date))
today = dt.today()
# Show today's date in mm/dd/yyyy format.
print(mdy(today))
dollar_amt=12345.678
# Show this big number in currency format.
print(to_curr(dollar_amt))

Check out these 10 amazing Python programming resources for more information.

About This Article

This article is from the book:

About the book authors:

John Shovic, PhD, is a computer science faculty member at the University of Idaho specializing in robotics and artificial intelligence.

Alan Simpson is a web development professional who has published more than 100 articles and books on technology.

Alan Simpson is the author of over 90 computer books on databases, Windows, Web site design and development, programming, and networking. His books are published throughout the world in over a dozen languages and have millions of copies. Alan has also taught introductory and advanced computer programming courses at San Diego State University and the UCSD Extension. He has served as a consultant on high-technology, educationoriented projects for the United States Navy and Air Force. Despite that, Alan has no fancy job title because he has never had a real job.

This article can be found in the category: