Make Field constructors keyword-only (#7632)

This commit is contained in:
Aarni Koskela 2021-08-06 12:14:52 +03:00 committed by GitHub
parent b215375125
commit fdb4931475
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 23 deletions

View File

@ -320,7 +320,7 @@ class Field:
default_empty_html = empty default_empty_html = empty
initial = None initial = None
def __init__(self, read_only=False, write_only=False, def __init__(self, *, read_only=False, write_only=False,
required=None, default=empty, initial=empty, source=None, required=None, default=empty, initial=empty, source=None,
label=None, help_text=None, style=None, label=None, help_text=None, style=None,
error_messages=None, validators=None, allow_null=False): error_messages=None, validators=None, allow_null=False):
@ -1163,14 +1163,14 @@ class DateTimeField(Field):
} }
datetime_parser = datetime.datetime.strptime datetime_parser = datetime.datetime.strptime
def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs): def __init__(self, format=empty, input_formats=None, default_timezone=None, **kwargs):
if format is not empty: if format is not empty:
self.format = format self.format = format
if input_formats is not None: if input_formats is not None:
self.input_formats = input_formats self.input_formats = input_formats
if default_timezone is not None: if default_timezone is not None:
self.timezone = default_timezone self.timezone = default_timezone
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def enforce_timezone(self, value): def enforce_timezone(self, value):
""" """
@ -1249,12 +1249,12 @@ class DateField(Field):
} }
datetime_parser = datetime.datetime.strptime datetime_parser = datetime.datetime.strptime
def __init__(self, format=empty, input_formats=None, *args, **kwargs): def __init__(self, format=empty, input_formats=None, **kwargs):
if format is not empty: if format is not empty:
self.format = format self.format = format
if input_formats is not None: if input_formats is not None:
self.input_formats = input_formats self.input_formats = input_formats
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def to_internal_value(self, value): def to_internal_value(self, value):
input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS) input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS)
@ -1315,12 +1315,12 @@ class TimeField(Field):
} }
datetime_parser = datetime.datetime.strptime datetime_parser = datetime.datetime.strptime
def __init__(self, format=empty, input_formats=None, *args, **kwargs): def __init__(self, format=empty, input_formats=None, **kwargs):
if format is not empty: if format is not empty:
self.format = format self.format = format
if input_formats is not None: if input_formats is not None:
self.input_formats = input_formats self.input_formats = input_formats
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def to_internal_value(self, value): def to_internal_value(self, value):
input_formats = getattr(self, 'input_formats', api_settings.TIME_INPUT_FORMATS) input_formats = getattr(self, 'input_formats', api_settings.TIME_INPUT_FORMATS)
@ -1470,9 +1470,9 @@ class MultipleChoiceField(ChoiceField):
} }
default_empty_html = [] default_empty_html = []
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
self.allow_empty = kwargs.pop('allow_empty', True) self.allow_empty = kwargs.pop('allow_empty', True)
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def get_value(self, dictionary): def get_value(self, dictionary):
if self.field_name not in dictionary: if self.field_name not in dictionary:
@ -1529,12 +1529,12 @@ class FileField(Field):
'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'), 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'),
} }
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
self.max_length = kwargs.pop('max_length', None) self.max_length = kwargs.pop('max_length', None)
self.allow_empty_file = kwargs.pop('allow_empty_file', False) self.allow_empty_file = kwargs.pop('allow_empty_file', False)
if 'use_url' in kwargs: if 'use_url' in kwargs:
self.use_url = kwargs.pop('use_url') self.use_url = kwargs.pop('use_url')
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def to_internal_value(self, data): def to_internal_value(self, data):
try: try:
@ -1578,9 +1578,9 @@ class ImageField(FileField):
), ),
} }
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField) self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField)
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def to_internal_value(self, data): def to_internal_value(self, data):
# Image validation is a bit grungy, so we'll just outright # Image validation is a bit grungy, so we'll just outright
@ -1595,8 +1595,8 @@ class ImageField(FileField):
# Composite field types... # Composite field types...
class _UnvalidatedField(Field): class _UnvalidatedField(Field):
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
super().__init__(*args, **kwargs) super().__init__(**kwargs)
self.allow_blank = True self.allow_blank = True
self.allow_null = True self.allow_null = True
@ -1617,7 +1617,7 @@ class ListField(Field):
'max_length': _('Ensure this field has no more than {max_length} elements.') 'max_length': _('Ensure this field has no more than {max_length} elements.')
} }
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.child = kwargs.pop('child', copy.deepcopy(self.child))
self.allow_empty = kwargs.pop('allow_empty', True) self.allow_empty = kwargs.pop('allow_empty', True)
self.max_length = kwargs.pop('max_length', None) self.max_length = kwargs.pop('max_length', None)
@ -1629,7 +1629,7 @@ class ListField(Field):
"Remove `source=` from the field declaration." "Remove `source=` from the field declaration."
) )
super().__init__(*args, **kwargs) super().__init__(**kwargs)
self.child.bind(field_name='', parent=self) self.child.bind(field_name='', parent=self)
if self.max_length is not None: if self.max_length is not None:
message = lazy_format(self.error_messages['max_length'], max_length=self.max_length) message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
@ -1694,7 +1694,7 @@ class DictField(Field):
'empty': _('This dictionary may not be empty.'), 'empty': _('This dictionary may not be empty.'),
} }
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.child = kwargs.pop('child', copy.deepcopy(self.child))
self.allow_empty = kwargs.pop('allow_empty', True) self.allow_empty = kwargs.pop('allow_empty', True)
@ -1704,7 +1704,7 @@ class DictField(Field):
"Remove `source=` from the field declaration." "Remove `source=` from the field declaration."
) )
super().__init__(*args, **kwargs) super().__init__(**kwargs)
self.child.bind(field_name='', parent=self) self.child.bind(field_name='', parent=self)
def get_value(self, dictionary): def get_value(self, dictionary):
@ -1753,8 +1753,8 @@ class DictField(Field):
class HStoreField(DictField): class HStoreField(DictField):
child = CharField(allow_blank=True, allow_null=True) child = CharField(allow_blank=True, allow_null=True)
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
super().__init__(*args, **kwargs) super().__init__(**kwargs)
assert isinstance(self.child, CharField), ( assert isinstance(self.child, CharField), (
"The `child` argument must be an instance of `CharField`, " "The `child` argument must be an instance of `CharField`, "
"as the hstore extension stores values as strings." "as the hstore extension stores values as strings."
@ -1769,11 +1769,11 @@ class JSONField(Field):
# Workaround for isinstance calls when importing the field isn't possible # Workaround for isinstance calls when importing the field isn't possible
_is_jsonfield = True _is_jsonfield = True
def __init__(self, *args, **kwargs): def __init__(self, **kwargs):
self.binary = kwargs.pop('binary', False) self.binary = kwargs.pop('binary', False)
self.encoder = kwargs.pop('encoder', None) self.encoder = kwargs.pop('encoder', None)
self.decoder = kwargs.pop('decoder', None) self.decoder = kwargs.pop('decoder', None)
super().__init__(*args, **kwargs) super().__init__(**kwargs)
def get_value(self, dictionary): def get_value(self, dictionary):
if html.is_html_input(dictionary) and self.field_name in dictionary: if html.is_html_input(dictionary) and self.field_name in dictionary:

View File

@ -2010,6 +2010,11 @@ class TestListField(FieldValues):
field.to_internal_value(input_value) field.to_internal_value(input_value)
assert exc_info.value.detail == ['Expected a list of items but got type "dict".'] assert exc_info.value.detail == ['Expected a list of items but got type "dict".']
def test_constructor_misuse_raises(self):
# Test that `ListField` can only be instantiated with keyword arguments
with pytest.raises(TypeError):
serializers.ListField(serializers.CharField())
class TestNestedListField(FieldValues): class TestNestedListField(FieldValues):
""" """