8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonの変数の名前を文字列として取得

Last updated at Posted at 2019-08-22

Pythonの変数の名前を文字列として取得

コードは冗長ですけど、僕みたいな素人にはこれがわかりやすいのでアップ。
参考にしたのはこちらです。基本的に同じですが、リンク先の方が本格的です。

注意点

正確に変数名を取得できない場合があるので注意。
具体的には、異なる複数の変数が以下等である場合、変数名を区別できない。

  1. -5から256までの同じ値を代入した時 (理由はこちら)
  2. 「参照渡し」された同じ値やオブジェクトである時
  3. 同じ文字列を代入した時
    また、この時複数の変数を区別して取得する方法はない
    詳しくは、本文下のshiracamusさんからのコメントを参照。
get_var_names.py
# !/usr/bin/env python3

a='aaa'
b=[1,2,3]


# only one variable
def get_var_name(var):
    for k,v in globals().items():
        if id(v) == id(var):
            name=k
    return name

get_var_name(a)
# 'a'


# from list, multiple variables
def get_var_names(vars):
    names=[]
    for var in vars:
        for k,v in globals().items():
            if id(v) == id(var):
                names.append(k)
    return names

get_var_names([a, b])
# ['a', 'b']

# 正確に変数名を取得できない場合があるので注意
a = 12345
b = a     # 参照渡し

get_var_name(a)
# 'b'
get_var_name(b)
# 'b'

環境

Ubuntu 18.04
Python 3.7.3

8
7
9

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?