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?

スター演算子を使う

0
Posted at

スター 1 つで JavaScript のスプレッド演算子

例 1

a = [0, 1, 2]
b = [*a, 3, 4] # JavaScriptでいう[...[0, 1, 2], 3, 4]

print(b) # [0, 1, 2, 3, 4]

a = {"key1": "value1"}
b = {**a, "key2": "value2"} # 辞書のマージ(シャロー)

print(a, b) # {'key1': 'value1'} {'key1': 'value1', 'key2': 'value2'}

例 2

ints = [0, 1, 2]


def func(*args: int) -> None:
    # args == (0, 1, 2)
    print(args)  # print((0, 1, 2))
    print(*args)  # print(0, 1, 2)


func(*ints)  # func(0, 1, 2)

例 3(応用)

import time
from typing import Callable


def intercept[T](func: Callable[[any], T], *args: any) -> T:
    print("Sleep before calling a function")
    time.sleep(1)
    print("Result:", func(*args))


def func(*args: any) -> bool:
    return len(args) >= 3


args = (0, 1, 2)

result_to_be_bool = intercept(func, *args)

Sleep before calling a function
Result: True

スター 2 つで dict として受け取れる

例 1

def func(**args) -> None:
    print(args)


func(a=0, b=1, c=2) # {'a': 0, 'b': 1, 'c': 2}
0
0
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
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?