Convert function arguments to string

Asked

Viewed 490 times

1

How to convert function arguments to string? Without having to type all arguments

I tried to solve it this way:

def teste(a, b, c, d, e='F9', f=1):
    for key, value in locals().items():
        key = str(value)
    message = ' '.join(['inicio', a, c, d, e, f, b])
    return message

t = teste('C6', 1, 2000, 'E4')
print(t)

But key in dictionary is not a function variable teste(), then the value converted to string is not passed to the variable.

The solution found was to convert all variables to string by typing the name of each variable:

def teste(a, b, c, d, e='F9', f=1):
    message = ' '.join(str(x) for x in ['inicio', a, c, d, e, f, b])
    return message


t = teste('C6', 1, 2000, 'E4')
print(t)

But how to accomplish this without having to type each variable, as for example with the use of locals()?

1 answer

2


If you have no need to distinguish between arguments, you can use the * in the declaration of the parameters of a function - this indicates that the function indicates a variable number of anonymous arguments that is already passed to the function as a tuple - and then, it is simple to convert all:

def teste(*args):
   return ' '.join(str(arg) for arg in args)

teste(1, 2, 3, 4, 5, 6)

If some of your parameters need a name, you can use ** to receive the parameters as a dictionary -

def teste(*args, **kw):
   return ' '.join(str(arg) for arg in (args + tuple(kw.values()) ) )

teste(1, 2, 3, 4, 5, 6, alo=7, mundo=8)

If you need to have default values in the parameters, as it is in your example, there is no way, or you will have to type the names in full, or use a combination of introspection techniques like what you are trying to do to iterate on the names of the variables. I don’t see how that could be good practice - a variable name is important and does something independent in your program, or, if you’re going to have several variables that you’re going to treat the same way, it’s best to put those values in a list or dictionary.

If you need to do this in several functions, it would be quite wrong to have to replicate this logic at all - ideally you use a decorator who transforms the types of the parameters when the function is called - and you already provide everything transformed into a string for your function.

The use of a decorator even allows its parameters to have a name in the final function (and the decorator uses generic arguments using "*" and "*"). Just doesn’t even account for standard arguments - these are not passed to the decorator.

def tudo_string(func):
    def decorador(*args, **kwargs):
         args = [str(arg) for arg in args]
         kwargs = {key: str(value) for key, value in kwargs.items()}
         return func(*args, **kwargs)
    return decorador

@tudo_string
def teste(a, b, c, d, e='F9', f=1):
    # Todos os parâmetros serão recebidos já convertidos em string aqui,
    # exceto o valor padrão de f que é dado "dentro" do decorador.
    ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.