Skip to content
Advertisement

Automatically change variable coming into function to string

Is there a way to automatically change the type of a variable when it arrives at a function, eg:

def my_func( str(x) ):
    return x

x = int(1)
type(x)

x = my_func(x)
type(x)

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:

def my_func(x):
    x = str(x)
    # rest of your logic here
    return x

If you don’t want to do this explicitly, you could (as suggested in the comments) use a decorator:

from functools import wraps


def string_all_input(func):
    # the "func" is the function you are decorating

    @wraps(func) # this preserves the function name
    def _wrapper(*args, **kwargs):
        # convert all positional args to strings
        string_args = [str(arg) for arg in args]
        # convert all keyword args to strings
        string_kwargs = {k: str(v) for k,v in kwargs.items()}
        # pass the stringified args and kwargs to the original function
        return func(*string_args, **string_kwargs)

    return _wrapper

# apply the decorator to your function definition
@string_all_input
def my_func(x):
    # rest of your logic here
    return x

type(my_func(123))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement