Is there a way to automatically change the type of a variable when it arrives at a function, eg:
JavaScript
x
9
1
def my_func( str(x) ):
2
return x
3
4
x = int(1)
5
type(x)
6
7
x = my_func(x)
8
type(x)
9
I know this code won’t work, but it’s just to explain my question.
I also know I can just do x = my_func(str(x))
, but I specifically want to make sure all variables coming into function will be string.
Advertisement
Answer
The simplest way to solve your problem would be to explicitly convert the input to a string, like so:
JavaScript
1
6
1
def my_func(x):
2
x = str(x)
3
# rest of your logic here
4
return x
5
6
If you don’t want to do this explicitly, you could (as suggested in the comments) use a decorator:
JavaScript
1
25
25
1
from functools import wraps
2
3
4
def string_all_input(func):
5
# the "func" is the function you are decorating
6
7
@wraps(func) # this preserves the function name
8
def _wrapper(*args, **kwargs):
9
# convert all positional args to strings
10
string_args = [str(arg) for arg in args]
11
# convert all keyword args to strings
12
string_kwargs = {k: str(v) for k,v in kwargs.items()}
13
# pass the stringified args and kwargs to the original function
14
return func(*string_args, **string_kwargs)
15
16
return _wrapper
17
18
# apply the decorator to your function definition
19
@string_all_input
20
def my_func(x):
21
# rest of your logic here
22
return x
23
24
type(my_func(123))
25