33

When I was exploring a solution for the StackOverflow problem, Python Use User Defined String Class, I came with this strange python behavior.

def overriden_print(x):
    print "Overriden in the past!"

from __future__ import print_function

print = overriden_print

print("Hello World!")

Output:

Overriden in the past!

Now, how can I get back the original print behavior in python interpreter?

Community
  • 1
  • 1
Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26

1 Answers1

62

Just delete the override:

del print

This deletes the name from the globals() dictionary, letting search fall back to the built-ins.

You can always refer directly to the built-in via the __builtin__ module as well:

import __builtin__

__builtin__.print('Printing with the original built-in')

In Python 3, the module has been renamed to builtins.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    this doesn't work inside functions with parameter names that match built-in names? `UnboundLocalError: local variable 'range' referenced before assignment` – endolith Jul 02 '15 at 04:19
  • @endolith: parameters are *local* names. I'm not sure what you are trying to do there; you cannot use a name both as a local and a global, so once you use `range` as a parameter you cannot use `del` on it to get the global again. – Martijn Pieters Jul 02 '15 at 07:53
  • print = None did not work. del print worked. Thanks for the tip. – manpreet singh Dec 07 '15 at 14:45
  • @noɥʇʎԀʎzɐɹƆ the `builtin` and `__builtin__` modules are *not* an implementation detail, only `__builtins__` reference in module globals is. – Martijn Pieters Sep 29 '19 at 17:03