14

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?

3 Answers 3

19

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

3 Comments

This is better than what I was going to attempt. I was going to do something horrible with __defaults__ (which apparently doesn't exist on builtin functions anyway ...)
@MartijnPieters Thanks, this is exactly what I was looking for. However, how is this different from defining a new function, like def myprint(*args): print(*args, end='-', sep'.') or using lambda like Lee suggested? Just curious, is this better in some way?
@PatrikLippojoki: functools.partial codifies defining your own wrapper function into one line. It's better in that it is shorter and clearer (in my view); it signals you are still just calling print() but with default arguments.
4

You can also use a lambda function:

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

5 Comments

functools.partial is good, just be aware that it only "became" available in Python 2.5+
Python 2.5 is rather old by now.
Indeed it is. I know of several vendors that haven't certified their product on anything past RHEL5.4 which still has 2.4 (!!) on it.
@Lee: Yes. But you can install newer versions side by side. No excuse. But I very well understand what you mean :) Microsoft would tell you in similar case the older system is not supported. Yes, it may be arrogant sometimes, but it is also pragmatic.
With this lambda, my_print can only accept one argument, which makes the function far less interesting. And of course, it defeats the purpose of the sep='-' .
2

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

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

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.