Get current column from formula

Hi everyone,

here is another useful little snippet that I’ll put on the RUC soon. It enables a formula to obtain the name of the column it resides in. Unless I’ve overlooked something, it does this fairly reliably (unlike this solution?). It might come in handy when writing functions intended for re-use across formulas, which is what I’m all about these days :slight_smile:

Hope it’s useful! If you find any errors or inconsistent behaviour, please let me know!

import inspect

def get_current_node(shift_stack_levels_by: int=0) -> str:
  stack = inspect.stack()
  starting_stack_level = 0
  for i in range(len(stack)):
    fn = stack[i].function
    try:
      tbl = stack[i].frame.f_locals["table"]
      if tbl == table and (fn ==  "get_current_node" or fn.startswith("_")):
        starting_stack_level = i+1
        table_id = getattr(tbl, "table_id", None) or tbl.table.table_id
    except KeyError:
      pass
  result = stack[starting_stack_level + shift_stack_levels_by]
  result_column = result.function
  result_table = result.frame.f_locals.get("table", None)
  result_table = getattr(result_table, "user_table", None) or result_table
  return result_table, result_column

return get_current_node
3 Likes