前提・実現したいこと
別のモジュールの中に記述したリストオブジェクト(名前はf_list)をimportする時、モジュールを引数で指定したいと思い、以下のようなコードを書きました。
$ vim ./test.py def test(module_name, obj_name): exec("from {module_name} import f_list") f_list = eval('f_list') if obj_name in f_list: print(True) else: print(False) if __name__ == '__maiin__': eval(input('>>> ')
発生している問題・エラーメッセージ
ここで、同じディレクトリの./factorial.pyのf_listを./test.pyでimportしてみます。
$ vim ./factorial.py f_list = ['fact'] def fact(n, m): if n == m: return m else: return n * fact(n-1)
$ python ./test.py >>> test("factorial", "fact")
すると以下のようなエラーを吐きます。
Traceback (most recent call last): File "test.py", line 11, in <module> eval(input('>>> ')) File "<string>", line 1, in <module> File "test.py", line 3, in test f_list = eval('f_list') File "<string>", line 1, in <module> NameError: name 'f_list' is not defined $ _
試したこと
print(eval("f_list"))と書き換えた./test.pyは動作します。
$ vim ./test.py def test(module_name): exec(f"from {module_name} import f_list") print(eval('f_list')) if __name__ == '__maiin__': eval(input('>>> ') $ python ./test.py >>> test('factorial') ['fact'] $ _
ですが以下のコードは動きません。
$ vim ./test.py def test(module_name): exec(f"from {module_name} import f_list") f_list = eval('f_list') print(f_list) if __name__ == '__maiin__': eval(input('>>> ') $ python ./test.py >>> test('factorial') Traceback (most recent call last): File "test.py", line 16, in <module> eval(input('>>> ')) File "<string>", line 1, in <module> File "test.py", line 3, in test f_list = eval('f_list') File "<string>", line 1, in <module> NameError: name 'f_list' is not defined $ _
つまるところ
execで文字列を式として評価してimportしたオブジェクトf_listが、関数の中で変数f_listとして使えないという問題に直面しています。f_list = eval('f_list')のように変数名を与えても動きません。しかしprint(eval('f_list')は動くので混乱しています。
補足情報(FW/ツールのバージョンなど)
Mac OS X (El Captian)
Anaconda3-5.2.0 (Python3.6)
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。