def test_main_use_case(): root = make_root_environment() root.define('zFoo', parse_expression('(+ aPar 7)')) root.define('aPar', 3) assert root.evaluate(parse_expression('(- zFoo 1)')) == 9 root.define('aPar', 4) assert root.evaluate(parse_expression('zFoo')) == 11 assert root.evaluate(parse_expression('zFoo - 1')) == 10
def test_evaluate_expressions(self, some_table: Table): env: Environment = make_root_environment().define('x', 42).define('y', 7) assert some_table.evaluate_expressions(env, inplace=False).df.iloc[1, 2] == 49 context_dict = {'x': 7, 'y': 9} assert some_table.evaluate_expressions(context_dict, inplace=False).df.iloc[1, 2] == 16 env.update([('y', 10)]) some_table.evaluate_expressions(env, inplace=True) assert some_table.df.iloc[1, 2] == 52
def evaluate_expressions(self, context: Union[Dict[str, pyscheme.Expression], pyscheme.Environment], *, inplace: bool = False): # TODO Replace context type hint with EvaluationContext defined above? """ Evaluate expressions in this Table based on the given context. :param context: Can be a pyscheme Environment, or a dict of symbols:values :param inplace: If False, returns a new Table. If True, evaluates expressions in-place instead. """ if isinstance(context, pyscheme.Environment): env = context else: env: pyscheme.Environment = pyscheme.make_root_environment() for k, v in context.items(): env.define(k, v) expression_cells = self._find_expression_cells(self._df) # TODO does this validation below make sense? It isn't currently possible with pyscheme.Environment... # # Validate context (check that it covers all symbols in source df) # source_df_symbols = {s for cell in param_cells for s in cell.symbols} # context_symbols = set(evaluation_context.keys()) # if not source_df_symbols.issubset(context_symbols): # raise ValueError(f'Evaluation context missing some symbols present in this Table: ' # f'{source_df_symbols - context_symbols}') if inplace: df = self._df else: df: pd.DataFrame = self._df.copy() # Evaluate for cell in expression_cells: cell.update_in_data_frame(df, env) if not inplace: t = Table(df=df, name=self.name, col_specs=self.col_specs, destinations=self.destinations, origin=self.origin) return t