Get a hash of a given module in python

This small function use the inspect and sha modules to return you a hash of the given module/class/function.
Note that we only hash the bytecode, so only really modified code will change the resulting hash.

import inspect

def get_module_hash(root, obj=None, hash=None, verbose=False):
if not obj:
obj = root
if verbose:
print obj.__name__
if not hash:
import sha
hash = sha.new()

for member in inspect.getmembers(obj):
name, child = member

if inspect.ismodule(child):
if child.__name__.startswith(root.__name__):
if child != root:
if verbose:
print child.__name__
hash = get_module_hash(root, child, hash, verbose)

if inspect.isclass(child):
if child.__module__.startswith(root.__name__):
if verbose:
print '  ', child.__name__
hash = get_module_hash(root, child, hash, verbose)

if inspect.ismethod(child):
if verbose:
print '    ', child.__name__
hash.update(child.im_func.func_code.co_code)

if inspect.isfunction(child):
if root.__name__ in child.func_code.co_filename:
if verbose:
print '  ', child.__name__
hash.update(child.func_code.co_code)
return hash

hash = get_module_hash(yourmodule)
print 'version hash:', hash.hexdigest()

Comments

Popular posts from this blog

Choosing a CRT-Shader for Youtube

Stars Audio Remastering