0

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.

ljc
  • 943
  • 2
  • 10
  • 26
  • 5
    You could write a _decorator_ to do that, but why? – jonrsharpe Nov 12 '21 at 12:58
  • Hi @jonrsharpe, how would that look then? – ljc Nov 12 '21 at 13:00
  • See e.g. https://wiki.python.org/moin/PythonDecorators – jonrsharpe Nov 12 '21 at 13:01
  • what do you want to do, if a variable is not `str`? – 576i Nov 12 '21 at 13:01
  • Yeah, outside of just writing validation at the head of the function, you probably need a decorator: https://stackoverflow.com/a/15858434/8382028 – ViaTech Nov 12 '21 at 13:01
  • whats wrong with just putting at the start of the function `x = str(x)` – Chris Doyle Nov 12 '21 at 13:02
  • Hi @ChrisDoyle, it's an extra line of code. Just wondering if something like what I asked exists, which to me seems simpler. – ljc Nov 12 '21 at 13:03
  • Hi @576i, the variable coming in is Path object, which in the function will always have to be a string. So thought there might be a way to just do it automatically without extra code – ljc Nov 12 '21 at 13:04
  • If it is `Path` object (i.e. `pathlib.Path`) why do you want to convert it to `str` and not work with `Path` object? – buran Nov 12 '21 at 13:41

1 Answers1

1

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))
PirateNinjas
  • 1,908
  • 1
  • 16
  • 21