## Copyright (c) 2006 Bruce Vaughan, BV Detailing & Design, Inc.

## All rights reserved.

## PrintDict.py Version 1.02

###############################################################

""" Return a formatted string of a sorted dictionary listing

    Library module PrintDict

    function 'formatDict'

    Place in directory 'SDS/2 root data'/macro/macrolib.

    Create the directory if it does not exist.

    This file can be executed as a stand alone parametric.

   

    Example import:

    from macrolib.PrintDict import formatDict

   

    Example usage:

    str1 = formatDict("Dialog Box 1 dictionary listing:", dd1())

    print str1

   

    The function returns a string containing all the defined variables and their values.

    It works with 'globals()', 'locals()' or any dictionary.

    This can be useful when debugging a parametric.

 

    Revision History:

    Version 1.01 (11/5/06) -  Add '\n' (newline) to line 'ret_str = hdr_str + "\n"'

    Version 1.02 (11/27/06) - Revise the way 'padstr' is calculated

"""

# SEE EXAMPLE USAGE IN 'test_formatDict()' BELOW

def formatDict(hdr_str, dd):

    listCopy = list(dd.keys())

    listCopy.sort()

    listLen = []

    for i in listCopy:

        listLen.append(len(i))

    ret_str = hdr_str + "\n"

    for i in listCopy:

        padStr = " " * (max(listLen) - len(i)) + "  "

        ret_str = ret_str + "Key = %s %s Value = %s\n" % (i, padStr, dd[i])

    return ret_str

 

#########################################################

def test_formatDict():

    # set default variable values

    stf_thk = 1.9

    stf_width = 50.0

    foo = "Work is no fun."

 

    # create a dictionary with new values

    dd = {'stf_thk':0.375, 'stf_width':2.5, 'foo':'Python is fun!'}

 

    print formatDict("Dictionary 'dd' listing:", dd)

 

    # list local variables before updating

    print formatDict("Local variables before updating locals:", locals())

    # Update local dictionary       

    for key, value in dd.items():

        exec "%s = %s" % (key, repr(value)) in None

 

    # print local variables after updating

    print formatDict("\nLocal variables after updating locals:", locals())

 

## END test_formatDict() ###############################

if __name__ == '__main__':

    try:

        test_formatDict()

    finally:

        del test_formatDict

        del formatDict

"""

print "\nLocal variables accessed directly:"

for k, v in locals().items():

    print k, "=", v

"""