I'm making a small program with Python and openpyxl. I have created a function and I would like to reuse it according to a conditional, I have seen that eval() can be dangerous for possible exploits of attackers.
But using the eval() method in a local program, where the conditionals are not passed by the user, is it dangerous? do you have any alternative to modify my code and use it the way I want without the use of eval()?
The function have to move the values from one or multiple cols to another col/cols depending on a certain condition.
The function doesn't work now, I want to clarify myself first and then I will write it. I hope you understand what I want to do.
def move_values_between_cols(col, condition, col_values_to_change, new_col_values):
wb = load_workbook(file_path)
ws = wb.active
for cell in ws[col]:
if eval(condition):
for pos in col_values_to_change:
ws.cell(row=cell.row, column=new_col_values[pos]).value = cell.value
wb.save(file_path)
Edit:
I receive 4 or 5 different types of excel sheets, all of them with the same information fields but sorted in different ways and some with extra columns. And I need them all with the same shape. I have a function for each type of excel that goes from how it is to how I want it. The condition is written by me.
Example of a function:
def type1():
function1()
function2()
move_values_between_cols('A', 'cell.value is None', ['B','C'], ['D', 'F']):
def type2():
function2()
function3()
move_values_between_cols('C', 'not isinstance(cell.value, str)', ['A','B'], ['D', 'F']):
CodePudding user response:
My suggestion is that you pass functions to move_values_between_cols instead of strings that need to be evaluated.
For example:
move_values_between_cols('A', lambda value: value is None, ['B','C'], ['D', 'F'])
and inside move_values_between_cols, check the condition with
if condition(cell.value):
instead of
if eval(condition):
CodePudding user response:
As suggested in the comments you could you lambda-functions instead of strings:
def move_values_between_cols(col, filter_func, col_values_to_change, new_col_values):
wb = load_workbook(file_path)
ws = wb.active
for cell in ws[col]:
if filter_func(cell):
for pos in col_values_to_change:
ws.cell(row=cell.row, column=new_col_values[pos]).value = cell.value
wb.save(file_path)
def type1():
function1()
function2()
move_values_between_cols('A', lambda cell: cell.value is None, ['B','C'], ['D', 'F']):
def type2():
function2()
function3()
move_values_between_cols('C', lambda cell: not isinstance(cell.value, str), ['A','B'], ['D', 'F']):
