Skip to content

Commit

Permalink
Refs #23919 -- Removed str() conversion of type and method __name__.
Browse files Browse the repository at this point in the history
  • Loading branch information
charettes committed Jan 19, 2017
1 parent 41e0033 commit 9695b14
Show file tree
Hide file tree
Showing 17 changed files with 42 additions and 43 deletions.
2 changes: 1 addition & 1 deletion django/core/servers/basehttp.py
Expand Up @@ -161,7 +161,7 @@ def handle(self):
def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer): def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer):
server_address = (addr, port) server_address = (addr, port)
if threading: if threading:
httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, server_cls), {}) httpd_cls = type('WSGIServer', (socketserver.ThreadingMixIn, server_cls), {})
else: else:
httpd_cls = server_cls httpd_cls = server_cls
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
Expand Down
2 changes: 1 addition & 1 deletion django/db/migrations/autodetector.py
Expand Up @@ -306,7 +306,7 @@ def _build_migration_list(self, graph=None):
# Make a migration! Well, only if there's stuff to put in it # Make a migration! Well, only if there's stuff to put in it
if dependencies or chopped: if dependencies or chopped:
if not self.generated_operations[app_label] or chop_mode: if not self.generated_operations[app_label] or chop_mode:
subclass = type(str("Migration"), (Migration,), {"operations": [], "dependencies": []}) subclass = type("Migration", (Migration,), {"operations": [], "dependencies": []})
instance = subclass("auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label) instance = subclass("auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label)
instance.dependencies = list(dependencies) instance.dependencies = list(dependencies)
instance.operations = chopped instance.operations = chopped
Expand Down
4 changes: 2 additions & 2 deletions django/db/migrations/state.py
Expand Up @@ -578,7 +578,7 @@ def render(self, apps):
# First, make a Meta object # First, make a Meta object
meta_contents = {'app_label': self.app_label, "apps": apps} meta_contents = {'app_label': self.app_label, "apps": apps}
meta_contents.update(self.options) meta_contents.update(self.options)
meta = type(str("Meta"), tuple(), meta_contents) meta = type("Meta", tuple(), meta_contents)
# Then, work out our bases # Then, work out our bases
try: try:
bases = tuple( bases = tuple(
Expand All @@ -595,7 +595,7 @@ def render(self, apps):
# Restore managers # Restore managers
body.update(self.construct_managers()) body.update(self.construct_managers())
# Then, make a Model object (apps.register_model is called in __new__) # Then, make a Model object (apps.register_model is called in __new__)
return type(str(self.name), bases, body) return type(self.name, bases, body)


def get_field_by_name(self, name): def get_field_by_name(self, name):
for fname, field in self.fields: for fname, field in self.fields:
Expand Down
4 changes: 2 additions & 2 deletions django/db/models/fields/related.py
Expand Up @@ -1023,7 +1023,7 @@ def set_managed(model, related, through):
to = 'to_%s' % to to = 'to_%s' % to
from_ = 'from_%s' % from_ from_ = 'from_%s' % from_


meta = type(str('Meta'), (), { meta = type('Meta', (), {
'db_table': field._get_m2m_db_table(klass._meta), 'db_table': field._get_m2m_db_table(klass._meta),
'auto_created': klass, 'auto_created': klass,
'app_label': klass._meta.app_label, 'app_label': klass._meta.app_label,
Expand All @@ -1034,7 +1034,7 @@ def set_managed(model, related, through):
'apps': field.model._meta.apps, 'apps': field.model._meta.apps,
}) })
# Construct and return the new class. # Construct and return the new class.
return type(str(name), (models.Model,), { return type(name, (models.Model,), {
'Meta': meta, 'Meta': meta,
'__module__': klass.__module__, '__module__': klass.__module__,
from_: models.ForeignKey( from_: models.ForeignKey(
Expand Down
4 changes: 2 additions & 2 deletions django/db/models/fields/related_descriptors.py
Expand Up @@ -94,7 +94,7 @@ def RelatedObjectDoesNotExist(self):
# related model might not be resolved yet; `rel.model` might still be # related model might not be resolved yet; `rel.model` might still be
# a string model reference. # a string model reference.
return type( return type(
str('RelatedObjectDoesNotExist'), 'RelatedObjectDoesNotExist',
(self.field.remote_field.model.DoesNotExist, AttributeError), (self.field.remote_field.model.DoesNotExist, AttributeError),
{} {}
) )
Expand Down Expand Up @@ -297,7 +297,7 @@ def RelatedObjectDoesNotExist(self):
# The exception isn't created at initialization time for the sake of # The exception isn't created at initialization time for the sake of
# consistency with `ForwardManyToOneDescriptor`. # consistency with `ForwardManyToOneDescriptor`.
return type( return type(
str('RelatedObjectDoesNotExist'), 'RelatedObjectDoesNotExist',
(self.related.related_model.DoesNotExist, AttributeError), (self.related.related_model.DoesNotExist, AttributeError),
{} {}
) )
Expand Down
2 changes: 1 addition & 1 deletion django/forms/formsets.py
Expand Up @@ -441,7 +441,7 @@ def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
'min_num': min_num, 'max_num': max_num, 'min_num': min_num, 'max_num': max_num,
'absolute_max': absolute_max, 'validate_min': validate_min, 'absolute_max': absolute_max, 'validate_min': validate_min,
'validate_max': validate_max} 'validate_max': validate_max}
return type(form.__name__ + str('FormSet'), (formset,), attrs) return type(form.__name__ + 'FormSet', (formset,), attrs)




def all_valid(formsets): def all_valid(formsets):
Expand Down
4 changes: 2 additions & 2 deletions django/forms/models.py
Expand Up @@ -518,11 +518,11 @@ def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
# If parent form class already has an inner Meta, the Meta we're # If parent form class already has an inner Meta, the Meta we're
# creating needs to inherit from the parent's inner meta. # creating needs to inherit from the parent's inner meta.
bases = (form.Meta,) if hasattr(form, 'Meta') else () bases = (form.Meta,) if hasattr(form, 'Meta') else ()
Meta = type(str('Meta'), bases, attrs) Meta = type('Meta', bases, attrs)
if formfield_callback: if formfield_callback:
Meta.formfield_callback = staticmethod(formfield_callback) Meta.formfield_callback = staticmethod(formfield_callback)
# Give this new form class a reasonable name. # Give this new form class a reasonable name.
class_name = model.__name__ + str('Form') class_name = model.__name__ + 'Form'


# Class attributes for the new form class. # Class attributes for the new form class.
form_class_attrs = { form_class_attrs = {
Expand Down
16 changes: 8 additions & 8 deletions tests/apps/tests.py
Expand Up @@ -197,10 +197,10 @@ def test_dynamic_load(self):
'app_label': "apps", 'app_label': "apps",
'apps': new_apps, 'apps': new_apps,
} }
meta = type(str("Meta"), tuple(), meta_contents) meta = type("Meta", tuple(), meta_contents)
body['Meta'] = meta body['Meta'] = meta
body['__module__'] = TotallyNormal.__module__ body['__module__'] = TotallyNormal.__module__
temp_model = type(str("SouthPonies"), (models.Model,), body) temp_model = type("SouthPonies", (models.Model,), body)
# Make sure it appeared in the right place! # Make sure it appeared in the right place!
self.assertListEqual(list(apps.get_app_config("apps").get_models()), old_models) self.assertListEqual(list(apps.get_app_config("apps").get_models()), old_models)
with self.assertRaises(LookupError): with self.assertRaises(LookupError):
Expand All @@ -218,31 +218,31 @@ def test_model_clash(self):
} }


body = {} body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents) body['Meta'] = type("Meta", tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__ body['__module__'] = TotallyNormal.__module__
type(str("SouthPonies"), (models.Model,), body) type("SouthPonies", (models.Model,), body)


# When __name__ and __module__ match we assume the module # When __name__ and __module__ match we assume the module
# was reloaded and issue a warning. This use-case is # was reloaded and issue a warning. This use-case is
# useful for REPL. Refs #23621. # useful for REPL. Refs #23621.
body = {} body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents) body['Meta'] = type("Meta", tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__ body['__module__'] = TotallyNormal.__module__
msg = ( msg = (
"Model 'apps.southponies' was already registered. " "Model 'apps.southponies' was already registered. "
"Reloading models is not advised as it can lead to inconsistencies, " "Reloading models is not advised as it can lead to inconsistencies, "
"most notably with related models." "most notably with related models."
) )
with self.assertRaisesMessage(RuntimeWarning, msg): with self.assertRaisesMessage(RuntimeWarning, msg):
type(str("SouthPonies"), (models.Model,), body) type("SouthPonies", (models.Model,), body)


# If it doesn't appear to be a reloaded module then we expect # If it doesn't appear to be a reloaded module then we expect
# a RuntimeError. # a RuntimeError.
body = {} body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents) body['Meta'] = type("Meta", tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__ + '.whatever' body['__module__'] = TotallyNormal.__module__ + '.whatever'
with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"): with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"):
type(str("SouthPonies"), (models.Model,), body) type("SouthPonies", (models.Model,), body)


def test_get_containing_app_config_apps_not_ready(self): def test_get_containing_app_config_apps_not_ready(self):
""" """
Expand Down
2 changes: 1 addition & 1 deletion tests/auth_tests/test_hashers.py
Expand Up @@ -429,7 +429,7 @@ def test_load_library_no_algorithm(self):
self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception)) self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception))


def test_load_library_importerror(self): def test_load_library_importerror(self):
PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'}) PlainHasher = type('PlainHasher', (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'})
# Python 3 adds quotes around module name # Python 3 adds quotes around module name
msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?" msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"
with self.assertRaisesRegex(ValueError, msg): with self.assertRaisesRegex(ValueError, msg):
Expand Down
4 changes: 2 additions & 2 deletions tests/invalid_models_tests/test_relative_fields.py
Expand Up @@ -661,7 +661,7 @@ class Parent(models.Model):
pass pass


for invalid_related_name in invalid_related_names: for invalid_related_name in invalid_related_names:
Child = type(str('Child%s') % str(invalid_related_name), (models.Model,), { Child = type('Child%s' % invalid_related_name, (models.Model,), {
'parent': models.ForeignKey('Parent', models.CASCADE, related_name=invalid_related_name), 'parent': models.ForeignKey('Parent', models.CASCADE, related_name=invalid_related_name),
'__module__': Parent.__module__, '__module__': Parent.__module__,
}) })
Expand Down Expand Up @@ -700,7 +700,7 @@ class Parent(models.Model):
pass pass


for related_name in related_names: for related_name in related_names:
Child = type(str('Child%s') % str(related_name), (models.Model,), { Child = type('Child%s' % related_name, (models.Model,), {
'parent': models.ForeignKey('Parent', models.CASCADE, related_name=related_name), 'parent': models.ForeignKey('Parent', models.CASCADE, related_name=related_name),
'__module__': Parent.__module__, '__module__': Parent.__module__,
}) })
Expand Down
2 changes: 1 addition & 1 deletion tests/migrations/test_state.py
Expand Up @@ -1058,7 +1058,7 @@ def create_model(self, name, foreign_keys=[], bases=(), abstract=False, proxy=Fa
'apps': self.apps, 'apps': self.apps,
'proxy': proxy, 'proxy': proxy,
} }
meta = type(str("Meta"), tuple(), meta_contents) meta = type("Meta", tuple(), meta_contents)
if not bases: if not bases:
bases = (models.Model,) bases = (models.Model,)
body = { body = {
Expand Down
10 changes: 5 additions & 5 deletions tests/migrations/test_writer.py
Expand Up @@ -542,7 +542,7 @@ def test_simple_migration(self):
'verbose_name_plural': 'My models', 'verbose_name_plural': 'My models',
} }


migration = type(str("Migration"), (migrations.Migration,), { migration = type("Migration", (migrations.Migration,), {
"operations": [ "operations": [
migrations.CreateModel("MyModel", tuple(fields.items()), options, (models.Model,)), migrations.CreateModel("MyModel", tuple(fields.items()), options, (models.Model,)),
migrations.CreateModel("MyModel2", tuple(fields.items()), bases=(models.Model,)), migrations.CreateModel("MyModel2", tuple(fields.items()), bases=(models.Model,)),
Expand Down Expand Up @@ -593,7 +593,7 @@ def test_migration_path(self):
self.assertEqual(writer.path, expected_path) self.assertEqual(writer.path, expected_path)


def test_custom_operation(self): def test_custom_operation(self):
migration = type(str("Migration"), (migrations.Migration,), { migration = type("Migration", (migrations.Migration,), {
"operations": [ "operations": [
custom_migration_operations.operations.TestOperation(), custom_migration_operations.operations.TestOperation(),
custom_migration_operations.operations.CreateModel(), custom_migration_operations.operations.CreateModel(),
Expand All @@ -615,7 +615,7 @@ def test_sorted_imports(self):
""" """
#24155 - Tests ordering of imports. #24155 - Tests ordering of imports.
""" """
migration = type(str("Migration"), (migrations.Migration,), { migration = type("Migration", (migrations.Migration,), {
"operations": [ "operations": [
migrations.AddField("mymodel", "myfield", models.DateTimeField( migrations.AddField("mymodel", "myfield", models.DateTimeField(
default=datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc), default=datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc),
Expand All @@ -635,7 +635,7 @@ def test_migration_file_header_comments(self):
""" """
Test comments at top of file. Test comments at top of file.
""" """
migration = type(str("Migration"), (migrations.Migration,), { migration = type("Migration", (migrations.Migration,), {
"operations": [] "operations": []
}) })
dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc)
Expand All @@ -655,7 +655,7 @@ def test_models_import_omitted(self):
""" """
django.db.models shouldn't be imported if unused. django.db.models shouldn't be imported if unused.
""" """
migration = type(str("Migration"), (migrations.Migration,), { migration = type("Migration", (migrations.Migration,), {
"operations": [ "operations": [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='model', name='model',
Expand Down
12 changes: 6 additions & 6 deletions tests/model_forms/tests.py
Expand Up @@ -2731,12 +2731,12 @@ class Form2(forms.Form):
foo = forms.IntegerField() foo = forms.IntegerField()


self.assertEqual(list(ModelForm().fields.keys()), ['name']) self.assertEqual(list(ModelForm().fields.keys()), ['name'])
self.assertEqual(list(type(str('NewForm'), (Mixin, Form), {})().fields.keys()), []) self.assertEqual(list(type('NewForm', (Mixin, Form), {})().fields.keys()), [])
self.assertEqual(list(type(str('NewForm'), (Form2, Mixin, Form), {})().fields.keys()), ['foo']) self.assertEqual(list(type('NewForm', (Form2, Mixin, Form), {})().fields.keys()), ['foo'])
self.assertEqual(list(type(str('NewForm'), (Mixin, ModelForm, Form), {})().fields.keys()), ['name']) self.assertEqual(list(type('NewForm', (Mixin, ModelForm, Form), {})().fields.keys()), ['name'])
self.assertEqual(list(type(str('NewForm'), (ModelForm, Mixin, Form), {})().fields.keys()), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Mixin, Form), {})().fields.keys()), ['name'])
self.assertEqual(list(type(str('NewForm'), (ModelForm, Form, Mixin), {})().fields.keys()), ['name', 'age']) self.assertEqual(list(type('NewForm', (ModelForm, Form, Mixin), {})().fields.keys()), ['name', 'age'])
self.assertEqual(list(type(str('NewForm'), (ModelForm, Form), {'age': None})().fields.keys()), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Form), {'age': None})().fields.keys()), ['name'])


def test_field_removal_name_clashes(self): def test_field_removal_name_clashes(self):
""" """
Expand Down
10 changes: 5 additions & 5 deletions tests/model_inheritance/test_abstract_inheritance.py
Expand Up @@ -322,11 +322,11 @@ def fields(model):
return list((f.name, f.__class__) for f in model._meta.get_fields()) return list((f.name, f.__class__) for f in model._meta.get_fields())


model_dict = {'__module__': 'model_inheritance'} model_dict = {'__module__': 'model_inheritance'}
model1 = type(str('Model1'), (AbstractModel, Mixin), model_dict.copy()) model1 = type('Model1', (AbstractModel, Mixin), model_dict.copy())
model2 = type(str('Model2'), (Mixin2, AbstractModel), model_dict.copy()) model2 = type('Model2', (Mixin2, AbstractModel), model_dict.copy())
model3 = type(str('Model3'), (DescendantMixin, AbstractModel), model_dict.copy()) model3 = type('Model3', (DescendantMixin, AbstractModel), model_dict.copy())
model4 = type(str('Model4'), (Mixin2, Mixin, AbstractModel), model_dict.copy()) model4 = type('Model4', (Mixin2, Mixin, AbstractModel), model_dict.copy())
model5 = type(str('Model5'), (Mixin2, ConcreteModel2, Mixin, AbstractModel), model_dict.copy()) model5 = type('Model5', (Mixin2, ConcreteModel2, Mixin, AbstractModel), model_dict.copy())


self.assertEqual( self.assertEqual(
fields(model1), fields(model1),
Expand Down
3 changes: 1 addition & 2 deletions tests/queryset_pickle/tests.py
Expand Up @@ -82,8 +82,7 @@ def test_model_pickle_m2m(self):
def test_model_pickle_dynamic(self): def test_model_pickle_dynamic(self):
class Meta: class Meta:
proxy = True proxy = True
dynclass = type(str("DynamicEventSubclass"), (Event, ), dynclass = type("DynamicEventSubclass", (Event, ), {'Meta': Meta, '__module__': Event.__module__})
{'Meta': Meta, '__module__': Event.__module__})
original = dynclass(pk=1) original = dynclass(pk=1)
dumped = pickle.dumps(original) dumped = pickle.dumps(original)
reloaded = pickle.loads(dumped) reloaded = pickle.loads(dumped)
Expand Down
2 changes: 1 addition & 1 deletion tests/servers/tests.py
Expand Up @@ -111,7 +111,7 @@ def test_port_bind(self):
Each LiveServerTestCase binds to a unique port or fails to start a Each LiveServerTestCase binds to a unique port or fails to start a
server thread when run concurrently (#26011). server thread when run concurrently (#26011).
""" """
TestCase = type(str("TestCase"), (LiveServerBase,), {}) TestCase = type("TestCase", (LiveServerBase,), {})
try: try:
TestCase.setUpClass() TestCase.setUpClass()
except socket.error as e: except socket.error as e:
Expand Down
2 changes: 1 addition & 1 deletion tests/validation/test_unique.py
Expand Up @@ -53,7 +53,7 @@ class M(models.Model):
bar = models.IntegerField() bar = models.IntegerField()
baz = models.IntegerField() baz = models.IntegerField()


Meta = type(str('Meta'), (), { Meta = type('Meta', (), {
'unique_together': unique_together, 'unique_together': unique_together,
'apps': Apps() 'apps': Apps()
}) })
Expand Down

0 comments on commit 9695b14

Please sign in to comment.