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

Grant Edwards grant.b.edwards at gmail.com
Mon Oct 9 17:19:52 EDT 2017


On 2017-10-09, John Black <jblack at nopam.com> wrote:

> I want to make sure I understand what this line is doing: 
>
>> oldprint = print
>
> Experimenting, I find this is not a rename because I can use both 
> function names.

Right it's not _changing_ a name.  It's _adding_ a name.

> It looks it literally copies the function "print" to 
> another function called "oldprint".

No, it binds a new name of 'oldprint' to the function to which 'print'
is bound.  It does not create a second function, nor does it remove
the binding of the name 'print' to that function.  It just adds a
second name that's also bound to that function.

> But now, I have a way to modify the builtin funciton "print" by
> referencing oldprint.  Without oldprint, I have no way to directly
> modify print?

Well... you can still access the builtin print via the module that
contains it:

   >>> def print(*args, **kw):
   ...   __builtins__.print(*args, sep='', **kw)
   ... 
   >>> print(1,2,3)

However, anytime you find yourself using double underscore stuff you
should think to yourself "I should find a better way to do that."

> def print(*args, **kw):
>     print(*args, sep='', **kw)
>
> meaning print calls print (itself) with sep=''.  But this failed and I 
> guess the reason is that it would keep calling itself recursively adding 
> sep='' each time?

Yep.

Just define a new function with a new name:

   def myprint(*args, **kw):
       print(*args, sep='', **kw)

Redefining builtins is just going get you sworn at down the road a
bit.  If not by yourself, then by somebody else...

-- 
Grant Edwards               grant.b.edwards        Yow! Used staples are good
                                  at               with SOY SAUCE!
                              gmail.com            




More information about the Python-list mailing list