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でのdebug用print効率化

Last updated at Posted at 2025-02-23

背景

pritn出力で変数名:値を表示させるための記載が煩わしい
例)

abc = 123
print(f"abc:{abc}")
出力
abc: 123

調査結果

3つの対策を検討した。

対策1

Python 3.8 以降で使用できる「f-string デバッグ」の機能を利用

abc = 123
print(f"{abc=}")
出力
abc: 123

対策2

Python 3.8 以降で関数を作成

def print_variable_name_and_value(variable, variable_name):
    """
    変数名と値を表示します。
    """
    print(f"{variable_name}: {variable}")

abc=123
print_variable_name_and_value(abc, "abc") # 明示的に変数名を渡す
出力
abc: 123

対策3

inspect関数を利用する。

import inspect

def print_var_value(var):
  frame = inspect.currentframe().f_back
  #print(frame.f_locals)
  names = []
  for k, v in frame.f_locals.items(): # k:変数名、v:変数の値
    if v is var: #値及びオブジェクトが一緒か確認する
      names.append(k)
  name = names[0]
  print(f"{name}: {var}")

abc=123
print_var_value(abc)
出力
abc: 123

結論

対策1を推奨。
対策3は記載する文字列数が少なく便利であるが、
for文が呼び出し元の関数の変数の数だけループするので、処理速度の観点で対策1or2の方がよさそう
対策1と2は記述量と関数作成の手間の観点で対策1がよさそう

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?