Is there a way to globally set the print function separator?

Steve D'Aprano steve+python at pearwood.info
Tue Oct 10 03:01:15 EDT 2017


On Tue, 10 Oct 2017 03:05 pm, John Black wrote:

>> functools.partial(print, sep='') is the winner, IMO.
> 
> Ok, I got that working too after someone told me I have to import
> functools.  Can you explain what it means?  It looks like it is not
> defining another function like the other solutions but is truly changing
> the defaults for the existing function print?

No. You are absolutely not changing the defaults for the actual built-in print
function. There is no support for that in Python.

What is happening is a bit more complex, but simplified:

- functools.partial is creating a new function-like object, almost
  identical to the built-in print in every way that matters except
  that it uses sep='';

- this special function-like object actually calls the true built-in
  print (which is why we can trust it will be almost identical);

- but you have changed the name "print" to refer to the customised
  version instead of the original.

(That change of name will only apply to the current module. Other modules will
still see the original print function.)


One way to convince yourself that this is the case is to look at the ID of the
print function before and after:


py> import functools
py> id(print)
19
py> print = functools.partial(print, sep='')
py> id(print)
20


The ID numbers are different, which proves they are different objects.

(If you try this on your computer, you will almost certainly get different ID
numbers than I did. The ID numbers are opaque integers with no inherent
meaning, and will vary according to the version of Python you have, and even
the history of what you have run in the current interpreter session.)

We can dig a little deeper, and inspect the new "print" function:

py> print.func
<built-in function print>

It is holding onto a reference to the original (which is how it can call the
original). We can confirm this:

py> id(print.func)
19


Same ID as the original.

(Note that this test is not *quite* definitive: ID numbers are only guaranteed
to be unique between objects which exist at the same time. If you delete an
object, so the garbage collector reclaims its memory and reuses it, it is
possible that the ID number may be reused as well.)



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list