以下のような方法を用いて,変数名を取得しているのですが,自作ライブラリから読み出すのが面倒なので,もっと標準的で簡単な方法を探しています.なにか良い方法はないでしょうか.
(メタプログラミングなどの知見はあまりないです.)
python
1def getVarNamesG(obj): 2 return [k for k, v in globals().items() if id(obj) == id(v)] 3 4print(getVarNamesG(x)) 5print(getVarNamesG(x)[0]) 6 7結果 8['x'] 9x
python
1def get_name(value): 2 import inspect 3 import re 4 5 bac_frame = inspect.currentframe().f_back # この関数の呼び出し元のフレームオブジェクトを取得。 6 # 呼び出し元のソースコードのリストからstring.whitespace(' \t\n\r\v\f')を削除して1行を取得。 7 bac_code = inspect.getframeinfo(bac_frame).code_context[0].replace(" ", "") 8 pos = bac_code.find("#") # コメントの開始位置を取得 9 if pos != -1: 10 bac_code = bac_code[:pos] # コメントがあるときはそれを削除。 11 name = re.search(r"\((.+)\)", bac_code).group(1) # 呼び出し元関数の引数の変数名を取得。 12 return name 13 14x = np.arange(10).reshape(5,2) 15name = get_name(x) 16print("{}=\n{}".format(name,x)) 17print() 18print("{}=\n{}".format(get_name(x),x)) 19 20結果 21x= 22[[0 1] 23 [2 3] 24 [4 5] 25 [6 7] 26 [8 9]] 27 28"{}=\n{}".format(get_name(x),x)= 29[[0 1] 30 [2 3] 31 [4 5] 32 [6 7] 33 [8 9]]
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。