As rookie

ルーキーインフラエンジニアがインフラのこと以外も結構書いてしまうブログ

pythonでつくったクラスのフィールドとかの確認

pythonインスタンスを作成するときに

h = Hoge(hoge_field='hoge')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'hoge_field' is not defined

とかなったことありませんか? あるあるですよね。

おそらくクラス変数の名前が想定しているものと違うものになっているのだろうと考えます。

クラスを定義しているところを確認すれば良いのですが、「名前何になってるんだ」ってすぐに確認する方法です。

>>> from tmp import Hoge
>>> dir(hoge)

これでクラスの変数、メソッドの一覧を確認できます。

オブジェクトの内容を表示してくます。

dir() の戻り値はリストです。ですので、

>>> 'hoge_field' in dir(Hoge)
True

で存在するか確認できます

文字列などのオブジェクトも同じように

# 文字列の特殊変数、メソッドを表示
>>> str = 'text'
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Djangoのモデルの変数名わからなくなったときに実行するとできたので、覚書です。 * tmp/models.py

from django.db import models

class Hoge(models.Model):
    hoge_field = models.CharField(max_length=200)

モデルの内容

python manage.py makemigrations
python manage.py shell
>>> from tmp import Hoge
>>> dir(Hoge)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', 'check', 'choice_set', 'clean', 'clean_fields', 'date_error_message', 'delete', 'from_db', 'full_clean', 'get_deferred_fields', 'get_next_by_pub_date', 'get_previous_by_pub_date', 'id', 'objects', 'pk', 'prepare_database_save', 'hoge_field', 'refresh_from_db', 'save', 'save_base', 'serializable_value', 'unique_error_message', 'validate_unique']

モデルの変数を確認するときに利用してみよう

以上