LoginSignup
14
13

More than 5 years have passed since last update.

Pythonの組み込み関数をラップする

Posted at

Python で組み込み関数と同じ名前の関数を作成したときに、その関数の中で本来の組み込み関数を呼び出したい場合、 builtins モジュール( マニュアル )を使うことで組み込みの関数を呼び出すことができる。

例えば組み込み関数 max をラップして使いたい場合は以下のように書ける。

sample.py
# -*- coding: utf-8-unix -*-
import builtins

class Foo(object):
    pass

def max(a, b):
    u"""組み込み関数をラップした関数
    """
    v1, v2 = a, b

    if isinstance(a, Foo):
        v1 = a.value

    if isinstance(b, Foo):
        v2 = b.value

    # 組み込み関数の呼び出し
    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

なお、 Python 2系では __builtin__ モジュール( 's'は付かない! )を使用することで同様のことが実現できる。

Python 2系と3系のどちらでも実行できるようにしたい場合は、モジュールのロード部分を以下のようにすればよい。

try:
    # Python 3.X 用
    import builtins
except ImportError:
    # Python 2.X 用
    import __builtin__ as builtins
14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13