If you create a function with the same name as a built-in function in Python and want to call the original built-in function in that function, the builtins
module (manual You can call built-in functions by using library / builtins.html)).
For example, if you want to wrap the built-in function max
and use it, you can write as follows.
sample.py
# -*- coding: utf-8-unix -*-
import builtins
class Foo(object):
pass
def max(a, b):
u"""A function that wraps a built-in function
"""
v1, v2 = a, b
if isinstance(a, Foo):
v1 = a.value
if isinstance(b, Foo):
v2 = b.value
#Calling built-in functions
return builtins.max(v1, v2)
if __name__ == '__main__':
obj = Foo()
obj.value = 10
print(max(20, obj)) # >>> 20
print(max(5, obj)) # >>> 10
print(max(5, 20)) # >>> 20
In Python 2 series, the same thing can be achieved by using the __builtin__
module (**'s' is not added! **).
If you want to be able to execute in both Python 2 series and 3 series, you can load the module as follows.
try:
# Python 3.For X
import builtins
except ImportError:
# Python 2.For X
import __builtin__ as builtins
Recommended Posts