Search code examples
pythonrexxoorexx

Would a Python dictionary be the equivalent data structure to a Rexx compound variable?


I'm working on rewriting a lengthy Rexx script into a Python program and I am trying to figure out the best way to emulate the functionality of a Rexx compound variable. Would a dictionary be the best bet? Obviously, a dictionary will behave differently and won't be exactly the same as a compound variable.


Solution

  • Python dictionaries and Rexx stems are both associative arrays. They differ a bit in how they behave. Rexx's rules are very simple:

    1. An array reference is split into the "stem" and the "tail", separated by a single dot.
    2. The stem is a variable name, case-independently. This is the dictionary.
    3. The tail is processed to identify an element of the array. It is split into one or more dot-separated substrings. Each substring is treated as a variable: if there is a variable with that case-independent name, its value is used instead of its name. Otherwise the name is uppercased and used. The string is put back together, dots and all. This is the key.
    4. The array can have a default value, set by stem. = value, which applies to all unset elements.

    So, the result of a an array reference stem.tailpart1.tailpart2.tailpart3 in Python is:

    def evaluate_tail(tail, outer_locals):
       result = []
       for element in tail.split('.'):
          if element in outer_locals:
             result.append(str(outer_locals[element]))
          else:
             result.append(str(element).upper())
       return '.'.join(result)
    
    array_default_value = 4
    stem = {'A.B.C': 1, 'A.9.C': 2, 'A..q': 3}
    b = 9
    d = 'q'
    
    tail1 = 'a.b.c'
    tail2 = 'a..b'
    tail3 = 'a..d'
    
    stem.get(evaluate_tail(tail1,locals()), array_default_value) # 'stem.a.b.c' >>> stem['A.9.C'] >>> 2
    stem.get(evaluate_tail(tail2,locals()), array_default_value) # 'stem.a..b' >>> stem['A..9'] (not found) >>> (default value) >>> 4
    stem.get(evaluate_tail(tail3,locals()), array_default_value) # 'stem.a..d' >>> stem['A..q'] >>> 3