I have a function called set_func
that is 25 lines long. Inside it calls update
.
def set_func(table: str, identifier=None, **kwargs) -> None:
... # does stuff with arguments
query = update(table, kwargs, identifier)
...
execute(query)
I want to declare a function called delete_func
that does the exact same thing, but instead of calling update
it would call delete
.
My code:
def delete_func(table: str, identifier=None) -> None:
global update
backup_update = deepcopy(update)
assert backup_update is not update
update = delete
try:
return set_func(table, identifier)
finally:
update = backup_update
This works, buy it seems bad practice. Is there another way to do this without changing set_func
? Is it bad code?
CodePudding user response:
Since functions are first class, I would probably pass whatever work was to be done into your method as a parameter. Alternatively, you could pass in a flag and internally determine how to process the work. I would definitely NOT change the implementation as you have done here even if it technically worked.
I might do something like this:
def fn_update(table: str, identifier, **kwargs) -> None:
# do whatever you do to just update
return "query"
def fn_delete(table: str, identifier, **kwargs) -> None:
# do whatever you do to just delete
return "query"
def set_func(fn_work, table: str, identifier=None, **kwargs) -> None:
... # does stuff with arguments
query = fn_work(table, identifier, kwargs)
...
execute(query)