0

Is there a way to change the default value of arguments of the print function ?

particularly these arguments:

file=sys.stdout
flush=False

For example throughout my code I would like to toggle between flush=True and flush=False without having to manually add the argument value to every print statement I have. Preferably by adding 1 line of code vs going to every print function and manually changing the value of the argument.

AnarKi
  • 857
  • 1
  • 7
  • 27
  • Is it an interactive program? How are you planning on toggling it without explicitly writing so in the program? – Abhinav Mathur Oct 12 '20 at 10:27
  • 1
    create new function passing those arguments then you can use that function – deadshot Oct 12 '20 at 10:29
  • Create Function for Custom Print and call that every time instead of Print – Vignesh Oct 12 '20 at 10:29
  • is there no way using something like `.func_defaults` ? – AnarKi Oct 12 '20 at 10:31
  • Does this answer your question? [How to overload print function to expand its functionality?](https://stackoverflow.com/questions/27621655/how-to-overload-print-function-to-expand-its-functionality) – 4.Pi.n Oct 12 '20 at 10:35
  • 1
    You can use [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial) to define your own prints: `print_flush = partial(print, flush=True)` – Tomerikoo Oct 12 '20 at 10:41

1 Answers1

1

You can use functools.partial to override defaults:

from functools import partial

print_and_flush = partial(print, flush=True)

Then you can switch between using print and print_and_flush.

Alternatively, you can get your behavior by defining a custom class:

class CustomPrinter:
    def __init__(self, print_func):
        self.print = print_func
        self.flush = False

    def __call__(self, *args, **kwargs):
        kwargs.setdefault('flush', self.flush)
        return self.print(*args, **kwargs)


print = CustomPrinter(print)
print('foo')
print.flush = True
print('bar')
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • Advice to OP: this kind of code makes it hard to understand and follow (when looking at a certain print statement you don't know if it is flushed or not). Either stick to the first option presented in this answer (`partial`) or to explicit arguments. – Tomerikoo Oct 12 '20 at 11:01
  • @Tomerikoo definitely, that is also why i didn't want to write another function which uses print in the first place – AnarKi Oct 12 '20 at 12:00
  • @AnarKi another function can be fine, consider you have functions like `print_and_flush` or `print_without_flush` that's pretty clear to an unfamiliar reader even without going to the definition... – Tomerikoo Oct 12 '20 at 14:39
  • @Tomerikoo actually i ended up “redefining” print with the partial function literally as in print = partial(print, flush=True). This was exactly what i wanted – AnarKi Oct 12 '20 at 17:38