LoginSignup
4
2

More than 5 years have passed since last update.

デコレータとyieldを使ってdictを返す関数でちょっと楽する方法

Posted at

以下のような戻り値に1つの関数を適用するだけのデコレータを作っておくと

returns.py
def returns(wrap_function):
    def decorator(f):
        def decorated(*args, **kwargs):
            return wrap_function(f(*args, **kwargs))
        return decorated
    return decorator

以下のコードを

sample_old.py
def times3_old(values):
    result = {}
    for v in values:
        result[v] = v * 3
    return result

print(times3_old([1, 3, 5]))  # {1: 3, 3: 9, 5: 15}

以下のように書くことができます

sample.py
@returns(dict)
def times3(values):
    for v in values:
        yield v, v * 3

print(times3([1, 3, 5]))  # {1: 3, 3: 9, 5: 15}
4
2
8

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