TAGS :Viewed: 2 - Published at: a few seconds ago

[ Local const in recursion call ]

Well... Code first.

def magic(node):
  spells_dict = {"AR_OP":ar_op_magic, "PRE_OP":pre_op_magic}
  if node:
    if node.text in spells_dict:
      return spells_dict[node.text](node)
    else:
      return magic(node.l) + magic(node.r)
  else:
    return ""

During recursion calls there will be created a lot of spells_dict copies. I know that I can make that dict global, but I don't want, because this dict related to magic function only. So, I can create some class and put spells_dict and function to it, but it don't looks like a good solution.

Is there any way how I can do it with only one copy of spells_dict?

Answer 1


I don't see any problems with a MAGIC_SPELLS constant. You can locale it near the magic function, so you know, the belong together:

def magic_default(node):
    return magic(node.l) + magic(node.r)

MAGIC_SPELLS = {
    'AR_OP': ar_op_magic,
    'PRE_OP': pre_op_magic,
}

def magic(node):
    if node:
        func = MAGIC_SPELLS.get(node.text, magic_default)
        return func(node)
    return ""