I have written the following function:
def get_id(arg_a: int, arg_b: int, arg_c: int, arg_d: int) -> str:
'''Construct some example id for stackoverflow.'''
if isinstance(arg_a, float):
arg_a = int(arg_a)
if isinstance(arg_b, float):
arg_b = int(arg_b)
if isinstance(arg_c, float):
arg_c = int(arg_c)
if isinstance(arg_d, float):
arg_d = int(arg_d)
return f'{arg_a}|{arg_b}|{arg_c}|{arg_d}'
When I started to refactor my program, I found this function to be written not in as much pythonic way as I would like, so I started to think, how to rewrite it. I found out, I could use exec() in combination with get_id.__code__.co_varnames, which will provide a tuple with function arguments to iterate over:
def get_id(arg_a: int, arg_b: int, arg_c: int, arg_d: int) -> str:
'''Construct some example id for stackoverflow.'''
for arg in get_id.__code__.co_varnames:
exec(f'{arg} = int({arg}) if isinstance({arg}, float) else {arg}')
return f'{arg_a}|{arg_b}|{arg_c}|{arg_d}'
But after that, I found out that exec() function is not suggested to be used in production programs from many reasons, which I understand. But I do not know, what to use instead of exec(). Please, could you help me, how to write my function in more general way and without exec() function?
Thanks for your help.
-
I see there are three answers already, but I still think that it is worth asking why you thought that exec was needed here in the first place. If you literally just remove it, and the f string inside it, you can just RUN what you are currently EXECing. Why did you think you needed to use exec? What were you stuck on that required that?Neil– Neil2019年12月13日 09:43:09 +00:00Commented Dec 13, 2019 at 9:43
-
1@Neil Because OP is doing variable variables...deceze– deceze ♦2019年12月13日 09:43:40 +00:00Commented Dec 13, 2019 at 9:43
-
oh i see. hmm okay.Neil– Neil2019年12月13日 09:45:14 +00:00Commented Dec 13, 2019 at 9:45
1 Answer 1
The most straight forward way is this:
def get_id(*args: int) -> str:
return '|'.join(map(str, map(int, args)))
Nothing happens if you put an int through int(), so you can apply it to floats and ints alike.
If you want to list your parameters explicitly one by one:
def get_id(arg_a: int, arg_b: int, arg_c: int, arg_d: int) -> str:
return '|'.join(map(str, map(int, (arg_a, arg_b, arg_c, arg_d))))