0
2

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】If文なしで動的に値と関数を切り替える

Last updated at Posted at 2025-08-28

Pythonライブラリ triggon は、動的に値や関数を柔軟に切り替えられ、if 文を減らしてコードを削減できるのが特徴です。
ここでは、このライブラリを使った簡単な例を2つ紹介します。


➀ 値と関数の切り替え

import random

from triggon import Triggon, TrigFunc

F = TrigFunc() # 遅延実行用のラッパー
tg = Triggon("num", new=F.random.randint(1, 100))

def func():
    # "num" が有効なら 0 から random.randint(1, 100) に切り替え
    num = tg.switch_lit("num", org=0)
    print(num) 

func()

tg.set_trigger("num") # "num" ラベルを有効化
func()

tg.revert("num") # 元の値に戻す
func()
# == 出力 ==
0
79 (1〜100のランダムな数値)
0

switch_lit() は、値が TrigFunc で遅延実行されている関数なら、自動的に実行されます。
TrigFunc は、対象の関数をインスタンス化してラップするだけなので、普通の関数の呼び出しのように使うことが可能です。

➁ 1つの変数に複数のインデックス値を切り替え

F = TrigFunc()

# "nums" は (index 0, index 1, index 2, index 3) の値を持つ
tg = Triggon("nums", new=(1, 2, 3, F.print("次の切り替えで0に戻ります!")))

x = 0
print(x)

tg.set_trigger("nums") # ラベル "nums" を有効化

tg.switch_var("nums", x)          # index 0 に切り替え
print(x)

tg.switch_var("nums", x, index=1) # index 1 に切り替え
print(x)

tg.switch_var("nums", x, index=2) # index 2 に切り替え
print(x)

# switch_var()も同様に、
# 値が TrigFunc による遅延実行関数なら、自動的に実行される
tg.switch_var("nums", x, index=3) # index 3 に切り替え

tg.revert("nums") # x を元の値に戻す
print(x)
# == 出力 ==
0
1
2
3
次の切り替えで0に戻ります!
0

revert() を使えば、何度切り替えても元の値に戻すことができます。


上記の例ではラベルを1つしか使っていませんが、ラベルはいくつでも定義できます。

triggonについて

triggon はベータ版から正式にリリースされ、2つの新しい関数と15以上の機能を追加しました!

主な機能は以下の通りです:

  • 値や関数を動的に切り替え
  • 任意のタイミングでの関数呼び出し、早期リターン
  • 早期リターン時に任意の値を返すことが可能
  • ほとんどの関数を遅延実行できる

このライブラリは、コードから if 文を減らすことを目的に作られました。
興味があればぜひ試してみてください!

🔗 PyPI → https://pypi.org/project/triggon
🔗 GitHub → https://github.com/tsuruko12/triggon

開発過程や学習記録などは X に投稿しています↓

🔗 X → @12tsuruko

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?