Lesser‑Known but Useful Python Functions and Features
This article introduces a collection of practical yet under‑utilized Python capabilities—including arbitrary‑argument functions, file searching with glob, debugging with inspect, unique ID generation, hashing, serialization, compression, and atexit shutdown hooks—providing code examples and explanations for each.
00. Functions with Arbitrary Number of Arguments
Python allows not only optional parameters but also functions that accept any number of positional arguments using the *args syntax, and keyword arguments with **kwargs .
def function(arg1="", arg2=""):
print "arg1: {0}".format(arg1)
print "arg2: {0}".format(arg2)
function("Hello", "World")
function()Using a tuple to collect remaining arguments:
def foo(*args):
# just use "*" to collect all remaining arguments into a tuple
numargs = len(args)
print "Number of arguments: {0}".format(numargs)
for i, x in enumerate(args):
print "Argument {0} is: {1}".format(i, x)
foo()
foo("hello")
foo("hello", "World", "Again")01. Using glob() to Find Files
The glob module provides pattern‑based file searching, a more powerful alternative to os.listdir() .
import glob
# get all py files
files = glob.glob('*.py')
print filesYou can combine multiple patterns with itertools.chain :
import itertools as it, glob
def multiple_file_types(*patterns):
return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
for filename in multiple_file_types("*.txt", "*.py"):
print filenameTo obtain absolute paths, add os.path.realpath() :
import itertools as it, glob, os
def multiple_file_types(*patterns):
return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
for filename in multiple_file_types("*.txt", "*.py"):
realpath = os.path.realpath(filename)
print realpath02. Debugging with inspect
The inspect module can retrieve call‑stack information, which is useful for debugging.
import logging, inspect
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s',
datefmt='%m-%d %H:%M')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bow')
def test():
frame, filename, line_number, function_name, lines, index = \
inspect.getouterframes(inspect.currentframe())[1]
print(frame, filename, line_number, function_name, lines, index)
test()03. Generating Unique IDs
Use the built‑in uuid module instead of hashing for true unique identifiers.
import uuid
result = uuid.uuid1()
print resultFor cryptographic hashes you can use hashlib or hmac :
import hmac, hashlib
key = '1'
data = 'a'
print hmac.new(key, data, hashlib.sha256).hexdigest()
m = hashlib.sha1()
m.update("The quick brown fox jumps over the lazy dog")
print m.hexdigest()04. Serialization
Python’s pickle module can serialize arbitrary objects, while json offers a language‑agnostic format.
import pickle
variable = ['hello', 42, [1, 'two'], 'apple']
# serialize content
file = open('serial.txt', 'w')
serialized_obj = pickle.dumps(variable)
file.write(serialized_obj)
file.close()
# unserialize to produce original content
target = open('serial.txt', 'r')
myObj = pickle.load(target)
print serialized_obj
print myObj import json
variable = ['hello', 42, [1, 'two'], 'apple']
print "Original {0} - {1}".format(variable, type(variable))
# encoding
encode = json.dumps(variable)
print "Encoded {0} - {1}".format(encode, type(encode))
# decoding
decoded = json.loads(encode)
print "Decoded {0} - {1}".format(decoded, type(decoded))05. Compressing Strings
The zlib module can compress and decompress large strings.
import zlib
string = """ Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
... (omitted for brevity) ...
"""
print "Original Size: {0}".format(len(string))
compressed = zlib.compress(string)
print "Compressed Size: {0}".format(len(compressed))
decompressed = zlib.decompress(compressed)
print "Decompressed Size: {0}".format(len(decompressed))06. Registering Shutdown Functions
The atexit module lets you run code automatically when the interpreter exits, even after unhandled exceptions.
import atexit, time, math
def microtime(get_as_float=False):
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
start_time = microtime(False)
atexit.register(start_time)
def shutdown():
global start_time
print "Execution took: {0} seconds".format(start_time)
atexit.register(shutdown)The article concludes by inviting readers to share other hidden Python tricks.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.