Skip to content

Commit

Permalink
[py3] Used six.with_metaclass wherever necessary.
Browse files Browse the repository at this point in the history
  • Loading branch information
aaugustin committed Jul 22, 2012
1 parent 7fa51a2 commit d11d45a
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 12 deletions.
4 changes: 2 additions & 2 deletions django/contrib/admin/options.py
Expand Up @@ -24,6 +24,7 @@
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.text import capfirst, get_text_list from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.utils.translation import ungettext from django.utils.translation import ungettext
Expand Down Expand Up @@ -57,9 +58,8 @@ class IncorrectLookupParameters(Exception):


csrf_protect_m = method_decorator(csrf_protect) csrf_protect_m = method_decorator(csrf_protect)


class BaseModelAdmin(object): class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)):
"""Functionality common to both ModelAdmin and InlineAdmin.""" """Functionality common to both ModelAdmin and InlineAdmin."""
__metaclass__ = forms.MediaDefiningClass


raw_id_fields = () raw_id_fields = ()
fields = None fields = None
Expand Down
18 changes: 14 additions & 4 deletions django/db/models/base.py
Expand Up @@ -24,6 +24,7 @@
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.functional import curry from django.utils.functional import curry
from django.utils.encoding import smart_str, force_unicode from django.utils.encoding import smart_str, force_unicode
from django.utils import six
from django.utils.text import get_text_list, capfirst from django.utils.text import get_text_list, capfirst




Expand Down Expand Up @@ -275,8 +276,8 @@ def __init__(self, db=None):
# This impacts validation only; it has no effect on the actual save. # This impacts validation only; it has no effect on the actual save.
self.adding = True self.adding = True


class Model(object):
__metaclass__ = ModelBase class ModelWithoutMeta(object):
_deferred = False _deferred = False


def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -369,7 +370,7 @@ def __init__(self, *args, **kwargs):
pass pass
if kwargs: if kwargs:
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]) raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
super(Model, self).__init__() super(ModelWithoutMeta, self).__init__()
signals.post_init.send(sender=self.__class__, instance=self) signals.post_init.send(sender=self.__class__, instance=self)


def __repr__(self): def __repr__(self):
Expand Down Expand Up @@ -401,7 +402,7 @@ def __reduce__(self):
only module-level classes can be pickled by the default path. only module-level classes can be pickled by the default path.
""" """
if not self._deferred: if not self._deferred:
return super(Model, self).__reduce__() return super(ModelWithoutMeta, self).__reduce__()
data = self.__dict__ data = self.__dict__
defers = [] defers = []
for field in self._meta.fields: for field in self._meta.fields:
Expand Down Expand Up @@ -876,6 +877,15 @@ def clean_fields(self, exclude=None):
raise ValidationError(errors) raise ValidationError(errors)




# For unknown reasons, six.with_metaclass doesn't work correctly for Model.
# Fallback to exec'ing the appropriate syntax for each Python version.

if six.PY3:
six.exec_("class Model(ModelWithoutMeta, metaclass=ModelBase): pass")
else:
six.exec_("class Model(ModelWithoutMeta): __metaclass__ = ModelBase")


############################################ ############################################
# HELPER FUNCTIONS (CURRIED MODEL METHODS) # # HELPER FUNCTIONS (CURRIED MODEL METHODS) #
############################################ ############################################
Expand Down
4 changes: 2 additions & 2 deletions django/forms/forms.py
Expand Up @@ -14,6 +14,7 @@
from django.utils.html import conditional_escape, format_html from django.utils.html import conditional_escape, format_html
from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils import six




__all__ = ('BaseForm', 'Form') __all__ = ('BaseForm', 'Form')
Expand Down Expand Up @@ -380,14 +381,13 @@ def visible_fields(self):
""" """
return [field for field in self if not field.is_hidden] return [field for field in self if not field.is_hidden]


class Form(BaseForm): class Form(six.with_metaclass(DeclarativeFieldsMetaclass, BaseForm)):
"A collection of Fields, plus their associated data." "A collection of Fields, plus their associated data."
# This is a separate class from BaseForm in order to abstract the way # This is a separate class from BaseForm in order to abstract the way
# self.fields is specified. This class (Form) is the one that does the # self.fields is specified. This class (Form) is the one that does the
# fancy metaclass stuff purely for the semantic sugar -- it allows one # fancy metaclass stuff purely for the semantic sugar -- it allows one
# to define a form using declarative syntax. # to define a form using declarative syntax.
# BaseForm itself has no way of designating self.fields. # BaseForm itself has no way of designating self.fields.
__metaclass__ = DeclarativeFieldsMetaclass


class BoundField(StrAndUnicode): class BoundField(StrAndUnicode):
"A Field plus data" "A Field plus data"
Expand Down
6 changes: 4 additions & 2 deletions django/forms/models.py
Expand Up @@ -15,6 +15,7 @@
MultipleHiddenInput, media_property) MultipleHiddenInput, media_property)
from django.utils.encoding import smart_unicode, force_unicode from django.utils.encoding import smart_unicode, force_unicode
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils import six
from django.utils.text import get_text_list, capfirst from django.utils.text import get_text_list, capfirst
from django.utils.translation import ugettext_lazy as _, ugettext from django.utils.translation import ugettext_lazy as _, ugettext


Expand Down Expand Up @@ -365,8 +366,8 @@ def save(self, commit=True):


save.alters_data = True save.alters_data = True


class ModelForm(BaseModelForm): class ModelForm(six.with_metaclass(ModelFormMetaclass, BaseModelForm)):
__metaclass__ = ModelFormMetaclass pass


def modelform_factory(model, form=ModelForm, fields=None, exclude=None, def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
formfield_callback=None, widgets=None): formfield_callback=None, widgets=None):
Expand Down Expand Up @@ -401,6 +402,7 @@ def modelform_factory(model, form=ModelForm, fields=None, exclude=None,


form_metaclass = ModelFormMetaclass form_metaclass = ModelFormMetaclass


# TODO: this doesn't work under Python 3.
if issubclass(form, BaseModelForm) and hasattr(form, '__metaclass__'): if issubclass(form, BaseModelForm) and hasattr(form, '__metaclass__'):
form_metaclass = form.__metaclass__ form_metaclass = form.__metaclass__


Expand Down
4 changes: 2 additions & 2 deletions django/forms/widgets.py
Expand Up @@ -17,6 +17,7 @@
from django.utils.encoding import StrAndUnicode, force_unicode from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils import datetime_safe, formats from django.utils import datetime_safe, formats
from django.utils import six


__all__ = ( __all__ = (
'Media', 'MediaDefiningClass', 'Widget', 'TextInput', 'PasswordInput', 'Media', 'MediaDefiningClass', 'Widget', 'TextInput', 'PasswordInput',
Expand Down Expand Up @@ -153,8 +154,7 @@ def __unicode__(self):
args.append(self.choices) args.append(self.choices)
return self.parent_widget.render(*args) return self.parent_widget.render(*args)


class Widget(object): class Widget(six.with_metaclass(MediaDefiningClass)):
__metaclass__ = MediaDefiningClass
is_hidden = False # Determines whether this corresponds to an <input type="hidden">. is_hidden = False # Determines whether this corresponds to an <input type="hidden">.
needs_multipart_form = False # Determines does this widget need multipart form needs_multipart_form = False # Determines does this widget need multipart form
is_localized = False is_localized = False
Expand Down

0 comments on commit d11d45a

Please sign in to comment.