views:

25

answers:

2

I have a form class that looks something like this:

class RegisterForm(Form):
    username = Field(model_field='username', filters=validators.minlength(3))

You'll notice that username is a class variable. I believe this means that Field will be constructed once the first time the RegisterForm is used (after apache is restarted). It will not be re-constructed between page reloads (unless a 2nd WSGI instance (?) is spawned, but we won't get into that). I noticed this because some of the values I've set in Field.__init__ are not being reset.

However, Form.__init__ does seem to be called each page reload. I guess that's because of the way I'm using it? I'm actually constructing it like form = RegisterForm(request) at each page request.

So... supposing I don't want the [class variables in] RegisterForm to be "cached" and have the Fields re-initialized at each request... how would I do that? (without modifying the syntax of RegisterForm; you can do whatever inside the base class, Form)

A: 

You could update the class variable each instantiation:

class ContactForm(forms.Form):
    username = Field(model_field='username', filters=validators.minlength(3))
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        ContactForm.username = Field(model_field='username', filters=validators.minlength(3))
amro
Fields are descriptors. This won't work.
Ignacio Vazquez-Abrams
A: 

You could define the class within a function. That way it gets constructed each time the function is called.

def gotclass(data):
  class InnerClass(object):
    someattr = DoSomethingWith(data)
  return InnerClass

MyNewClass = gotclass(42)
someobj = MyNewClass()
Ignacio Vazquez-Abrams