#15127: form.fields is still tied to class variables
------------------------+---------------------------------------------------
 Reporter:  absoludity  |       Owner:  nobody    
   Status:  new         |   Milestone:            
Component:  Forms       |     Version:  SVN       
 Keywords:              |       Stage:  Unreviewed
Has_patch:  0           |  
------------------------+---------------------------------------------------
 From django.forms.forms.BaseForm.__init__, it seems the intention is that
 a form's self.fields should be safe to update

         # The base_fields class attribute is the *class-wide* definition
 of
         # fields. Because a particular *instance* of the class might want
 to
         # alter self.fields, we create self.fields here by copying
 base_fields.
         # Instances should always modify self.fields; they should not
 modify
         # self.base_fields.
         self.fields = deepcopy(self.base_fields)

 Yet
 {{{
 In [1]: from django import forms


 In [5]: class MyForm(forms.Form):
     title = forms.ChoiceField(choices=(('mr', 'Mr.'), ('mrs', 'Mrs.')))
    ...:     def __init__(self, *args, **kwargs):
    ...:         super(MyForm, self).__init__(*args, **kwargs)
    ...:         self.fields['title'].choices += [('you', 'who')]
    ...:

 In [7]: f1 = MyForm()

 In [8]: f1.fields['title'].choices
 Out[8]: [('mr', 'Mr.'), ('mrs', 'Mrs.'), ('you', 'who')]

 In [9]: f2 = MyForm()

 In [10]: f2.fields['title'].choices
 Out[10]: [('mr', 'Mr.'), ('mrs', 'Mrs.'), ('you', 'who'), ('you', 'who')]

 In [11]: f3 = MyForm()

 In [12]: f3.fields['title'].choices
 Out[12]:
 [('mr', 'Mr.'),
  ('mrs', 'Mrs.'),
  ('you', 'who'),
  ('you', 'who'),
  ('you', 'who')]

 In [17]: f3.base_fields['title']
 Out[17]: <django.forms.fields.ChoiceField object at 0x26cc910>

 In [18]: f3.fields['title']
 Out[18]: <django.forms.fields.ChoiceField object at 0x26ccb10>

 In [19]: f3.base_fields['title'].choices
 Out[19]:
 [('mr', 'Mr.'),
  ('mrs', 'Mrs.'),
  ('you', 'who'),
  ('you', 'who'),
  ('you', 'who')]
 }}}

 So it seems that the instance field is definitely a deep copy, but the
 attributes of are not. A friend then pointed out Field.__deepcopy__:

 http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L193

 which explains why the attributes are shared, but not whether this affect
 is intentional.

-- 
Ticket URL: <http://code.djangoproject.com/ticket/15127>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to django-updates@googlegroups.com.
To unsubscribe from this group, send email to 
django-updates+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en.

Reply via email to