Patrik Lippojoki
Patrik Lippojoki

Reputation: 1643

Python 3: Change default values of existing function's parameters?

I'm creating a program which will eventually have like 500 calls for print function, and some others too. Each of these functions will take the exact same parameters every time, like this:

print(a, end='-', sep='.')
print(b, end='-', sep='.')
print(c, end='-', sep='.')
print(..., end='-', sep='.')

Is there a way to change the default values of print function's parameters? So that I wouldn't have to type end='-', sep='.' every time?

Upvotes: 14

Views: 3321

Answers (3)

CG poly
CG poly

Reputation: 56

There is also a method that allows multiple parameters and works with lambdas:

my_print = lambda *args: print(*args, end="-", sep=".")

Upvotes: 2

Lee
Lee

Reputation: 611

You can also use a lambda function:

my_print = lambda x: print(x, end='-', sep='-')
my_print(a)
my_print(b)
my_print(c)

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121366

You can define a special version of print() using functools.partial() to give it default arguments:

from functools import partial

myprint = partial(print, end='-', sep='.')

and myprint() will then use those defaults throughout your code:

myprint(a)
myprint(b)
myprint(c)

Upvotes: 19

Related Questions