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.
...
Related
– danieltakeshi