Home > Mobile >  How can I call a built-in function, if the function is already overrided in Python3
How can I call a built-in function, if the function is already overrided in Python3

Time:02-15

Now I just tried to test if I can call built-in function inside overrided function in Python3, as follows:

def print(val=0):
    print("TEST")  # How can I call the original `print()` here to avoid RecursionError


print(10)

But the following error thrown. It makes sense.

>>> RecursionError: maximum recursion depth exceeded

I am curious if there is ways to call an original built-in function inside its overrided function, such as sys.__builtin__.print() I guess.

Thank you.

CodePudding user response:

Builtins are available in a module called builtins. Makes sense!

import builtins

def print(val=0):
    builtins.print("TEST")  # How can I call the original `print()` here to avoid RecursionError

print(10)

CodePudding user response:

You can use the builtins module to reference the built in print

import builtins
def print(val=0):
    builtins.print('TEST')

CodePudding user response:

I am posting same answer because I was beaten only by 2 minutes:

this solution in for python3 only python2 used import __builtin__

import builtins 

def print(val=0):
    builtins.print("TEST")  # How can I call the original `print()` here to avoid RecursionError


print(10)

output:

TEST

this works too:

def print(val=0):
    global print
    del print 
    print("TEST")  # How can I call the original `print()` here to avoid RecursionError


print(10)

see here for duplicated post

How to get back an overridden python built-in function?

CodePudding user response:

try this

import builtin

def print(val=0):
builtin.print('TEST')

print(10)

  • Related