0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの*と**について今更まとめる

0
Posted at

概要

  • シングルアスタリスク(*)とダブルアスタリスク(**)をあいまいに理解していたので、まとめてみました
  • 変数名のargsやkwargsは任意でなんでもよいです

* (シングルアスタリスク) の使い方

  • *args: タプルやリストをアンパック(展開)できる
def example_func(a, b, c):
    return a + b + c

args = [1, 2, 3]
example_func(*args) # example_func(1, 2, 3)と同義

** (ダブルアスタリスク) の使い方

  • **kwargs: 辞書をキーワード引数としてアンパック(展開)できる
def example_func(a, b, c):
    return a + b + c

kwargs = {"a": 1, "b": 2, "c": 3}
example_func(**kwargs) # example_func(a=1, b=2, c=3)と同義

応用

  • 辞書のアンパックをそのままquerysetに突っ込める
# 事前に必須のaにフィルターをかけるqueryを作成
filter_kwargs = {"a": self.a}
    
# cが0でない場合のみbにフィルターをかける条件を追加
if self.c != 0:
    filter_kwargs["b"] = self.b

# 最後にfilterを実行(ここで初めてSQLが発行される)
self.d = XXX.objects.filter(
    **filter_kwargs # ここで辞書がアンパックされる
).order_by("a")

上記は
self.c == 0 の場合:a のみでフィルタリング
self.c != 0 の場合:a + b でフィルタリング
される挙動になる

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?