I am trying to build a helper function that would take a certain number of strings and return a another string which is the parameters part of the function definition.
I want to build a function definition on the fly. I am not familiar with the number of parameters. The function must be capable of returning a string with proper values For example, I want this generate_function_def_on_fly(args:dict) to dynamically ouput ( {},{},{},{}).format(arg1, arg2, arg3). The dict will also have the data type of the arg, so if the datatype is of string it has to output the varibales with quote
Example:
arg_dict={
"num_value":"number"
"string_value": "string"
}
num_value = 5
string_value = "hello"
generate_function_def_on_fly(arg_dict) should output : (num_value, string_value) which will evaluate to (5, 'hello').
My Use case : I am calling a stored procedure from my code, and I have to dynamically pass arguments to it, I am getting this arguments(arg_dict) from a config file. I have to generate the calling part with proper qualifiers. i.e quotes for strings and no quotes for numbers.
Making it a bit more clear: I want to achieve this:
def generate_args_on_fly(args:dict):
# return ({id},' {name} ' )
args_dict = {
"id" : "number",
"name" : "string"
}
generate_args_on_fly(args_dict) # return ({id},' {name} ' )
I would like to use this with f"call {schema}.{stored_procedure}" return value from generate_args_on_fly(args_dict)
CodePudding user response:
I'm not entirely sure if this is what you're looking for, but I guess you could try with f-strings to see if it solves the issue:
>>> num_value = 5
>>> string_value = "hello"
>>> f'({num_value!r}, {string_value!r})'
"(5, 'hello')"
For the dynamic equivalent of str.format
or f-strings, you could create a wrapper function like how you had intended, and just call repr()
on each argument:
def generate_function_def_on_fly(*args):
return f'({", ".join(repr(a) for a in args)})'
num_value = 5
string_value = "hello"
print(generate_function_def_on_fly(num_value, string_value)) # (5, 'hello')