6

最初に少し背景を説明します... Django でのフォームの実装を理解するために (そして途中でいくつかの Python を学ぶために)、フォームの Django ソース コードを調べていました。Django は DeclaredMetaFields MetaClassを使用してフォームを実装します。

これは、Django のようなフォーム実装の非常に大雑把なクラス図です ( gist のサンプル コードへのリンク)。

ContactForm の Django フォームのような実装 - クラス図

そして、これがインスタンス図です。

ContactForm の Django フォームのような実装 - インスタンス図

これは、メタクラスに頼らない非常に大まかな同じクラスの実装です ( gist のサンプル コードへのリンク)。

ContactForm の単純で大雑把な実装

メタクラスの概念などを理解し、Django コードがどのように機能するかを理解しています。それでは質問です。

  1. 構文のエレガンスなどの明白な利点以外に、メタクラスの実装に他の利点はありますか?
  2. BoundField のような中間オブジェクトに頼ることなく、メタクラスのような実装は可能ですか?
4

1 に答える 1

2

Well syntactical benefits matters a lot. After all even classes in OOP languages is just a syntactical benefit of the language.

In your example of very crude implementation of meta-class-less form implementation you describe fields in Dict. Well you might have overlooked that it is actually SortedDict, because ordering of fields matters. So I'll need to define fields_order list as well.

Next big thing is ModelForm. Meta-class approach allows to simply say which Model do I use and which fields in Meta attribute and it automatically creates and maps fields to model. Without Metaclass approach I would probably have to use something like CreateFieldsFromModel and MapFieldsToModel. Or you might do that for me in __init__ method. But wait, __init__ method is already complex enough with lots of arguments like data, initial, files, and more.

class MyForm(Form):
    fields = {
        'one': ...
        ...
    }
    fields_order = [...]
    model_fields = ???

Class MyForm2(MyForm):
    fields = MyForm.fields + {...}

# ... hey this API sucks! I think I'll go with another framework.

And there are many more things which can be configured in forms and everything is documented.

So for me, because of huge configuration logic, it looks like Form just asks to be implemented through definition-object and factory-logic. And here comes python with its metaclasses to hide the factory from the user. And it is cool because it makes beginners to think less.

And well yea its syntactical sugar all around and its all about making easy to use API.

And yes it is possible not to use Metaclasses/BoundField or whatever else. In the end it is possible to write all implementation of forms in one function and have all definition in one big dict (or xml?) But will that be easy to use, easy to understand, easy to extend?

于 2011-03-30T08:07:01.960 に答える