2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ネストした関数定義のユースケース

Posted at

変数xの型がyでないとエラーとなる関数is_y(x)を、次のように複数の型に対して作成するための関数is_type_factoryの実装方法のメモです。

config.py
is_int = is_type_factory(int)
is_bool = is_type_factory(bool)
is_float = is_type_factory(float)
is_str = is_type_factory(str)
is_unicode = is_type_factory(compat.text_type)
is_text = is_instance_factory((str, bytes))

[pandas]
(https://github.com/pandas-dev/pandas/blob/master/pandas/core/config.py)のソースで見かけました。

関数定義のネストはこういう風に使うのかという例です。is_type_factoryに渡された引数_typeは、返される関数オブジェクトinnerの中では静的な変数の役割をしています。

config.py
def is_type_factory(_type):
    """

    Parameters
    ----------
    `_type` - a type to be compared against (e.g. type(x) == `_type`)

    Returns
    -------
    validator - a function of a single argument x , which returns the
                True if type(x) is equal to `_type`

    """

    def inner(x):
        if type(x) != _type:
            raise ValueError("Value must have type '%s'" % str(_type))

    return inner

2
1
3

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?