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.

9
  • 5
    You could write a decorator to do that, but why? Commented Nov 12, 2021 at 12:58
  • Hi @jonrsharpe, how would that look then? Commented Nov 12, 2021 at 13:00
  • See e.g. wiki.python.org/moin/PythonDecorators Commented Nov 12, 2021 at 13:01
  • what do you want to do, if a variable is not str? Commented Nov 12, 2021 at 13:01
  • Yeah, outside of just writing validation at the head of the function, you probably need a decorator: stackoverflow.com/a/15858434/8382028 Commented Nov 12, 2021 at 13:01

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.