LoginSignup
32
26

More than 5 years have passed since last update.

変数の変数名を文字列で取得する。

Last updated at Posted at 2014-01-14

ちょっとデバッグ用に欲しかったので自作。
pythonなら、名前空間の組み込み変数が用意されているのでそれに検索をかける。
(名前空間の変数locals()globals()を使う。)
変数の参照は一意ではないが、変数の参照先は一意(・・・ですよね?)であることを利用する。
(識別子関数id()を使う。)

def getVarsNames( _vars, symboltable ) :
    """
    This is wrapper of getVarName() for a list references.
    """
    return [ getVarName( var, symboltable ) for var in _vars ]

def getVarName( var, symboltable, error=None ) :
    """
    Return a var's name as a string.\nThis funciton require a symboltable(returned value of globals() or locals()) in the name space where you search the var's name.\nIf you set error='exception', this raise a ValueError when the searching failed.
    """
    for k,v in symboltable.iteritems() :
        if id(v) == id(var) :
            return k
    else :
        if error == "exception" :
            raise ValueError("Undefined function is mixed in subspace?")
        else:
            return error

if __name__ == "__main__":
    a = 4
    b = "ahoo"
    print getVarsNames([a,b,"c"],locals())

返り値はこれ。

['a', 'b', None]

どうだろう?重ねてネストした関数の中から呼び出したりすると、どうなるかな?

追記:例外送出のところは、ご自由にw

32
26
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
32
26