Skip to content

Instantly share code, notes, and snippets.

@pgollakota
Created March 30, 2011 00:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgollakota/893653 to your computer and use it in GitHub Desktop.
Save pgollakota/893653 to your computer and use it in GitHub Desktop.
# Django-like implementation
class BoundField(object):
def __init__(self, form, field, name):
self.form = form
self.field = field
self.name = name
def _data(self):
return self.field.value_from_datadict(self.form.data, self.name)
data = property(_data)
class CharField(object):
def value_from_datadict(self, data, text):
return data.get(text, None)
class DeclaredMetaFields(type):
def __new__(cls, name, bases, attrs):
fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if isinstance(obj, CharField)]
attrs['fields'] = dict(fields)
return type.__new__(cls, name, bases, attrs)
class Form(object):
__metaclass__ = DeclaredMetaFields
def __init__(self, data=None):
self.data = data or {}
def __getitem__(self, name):
try:
field = self.fields[name]
except KeyError:
raise KeyError('Key %r not found in Form' % name)
return BoundField(self, field, name)
class ContactForm(Form):
first_name = CharField()
last_name = CharField()
email = CharField()
c = ContactForm({'first_name':'James', 'last_name':'Bond'})
# The following line prints
# James Bond
print c['first_name'].data, c['last_name'].data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment