3
1

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 1 year has passed since last update.

pythonで変数が存在するか確かめる

Posted at

概要

python で変数が定義されていないとエラーが発生するかと思います。
エラーを防ぐ方法に例外処理であるtry exceptがあると思いますがその方法以外で
変数が定義されていないことを確かめたいと思います。

内容

まずはよくあるエラーから

function1=3.1415
print(function2)

# => NameError: name 'function2' is not defined

もちろんfunction2は定義されていないのでエラーを発生します。
例外処理であるtry exceptを用いると

try:
    function1=3.1415
    print(function2)
except:
    print("err")

# => err

これ以外の方法にlocal関数を使用する方法があります。

function1=3.1415
if 'function1' in locals():
    print('exist')
else:
    print('not exist')

#print(function2)
if 'function2' in locals():
    print('exist')
else:
    print('not exist')

# => exist
# => not exist

とできます。
強制的にエラーが発生してexcept関数を通さなくてもよいので使用の幅が広がるかと思います。
local関数を使用する場合はダブルクオート シングルクオートで変数を囲ってください。

まとめ

強制的にエラーが発生させずに変数が存在するかを、確かめることができました。
コメント等あれば、この記事にコメントお願いします。

3
1
2

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?