tropicbirdのブログ

備忘録です。

【備忘録】ax = ax or plt.gca()の記載の意味とPythonにおけるorの挙動

・以下の関数のax = ax or plt.gca()はaxの指定があればそれを適用し、指定が無ければmatplotlibによって作成するという意味。

def plot_something(data, ax=None, **kwargs):
    ax = ax or plt.gca()
    # Do some cool data transformations...
    return ax.boxplot(data, **kwargs)

引用元(ax = ax or plt.gca())
stackoverflow.com


Pythonにおける x or yの挙動は以下の通り。したがって、上記の関数では、ax=ax or plt.gca()が意図した通りに挙動する。

if bool(x):  # xの論理値がTrueなら
    return x  # yを見ることなく、しかもTrueではなくxそのものをリターン
else:  # xの論理値がFalseなら
    return y  # bool(y) ではなく、yそのものをリターン

引用元(Pythonのorの挙動)
qiita.com