Refs #23919 -- Removed str() conversion of type and method __name__.

This commit is contained in:
Simon Charette 2017-01-19 09:48:01 -05:00
parent 41e0033caf
commit 9695b14982
17 changed files with 42 additions and 43 deletions

View File

@ -161,7 +161,7 @@ class WSGIRequestHandler(simple_server.WSGIRequestHandler):
def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer):
server_address = (addr, port)
if threading:
httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, server_cls), {})
httpd_cls = type('WSGIServer', (socketserver.ThreadingMixIn, server_cls), {})
else:
httpd_cls = server_cls
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)

View File

@ -306,7 +306,7 @@ class MigrationAutodetector:
# Make a migration! Well, only if there's stuff to put in it
if dependencies or chopped:
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.dependencies = list(dependencies)
instance.operations = chopped

View File

@ -578,7 +578,7 @@ class ModelState:
# First, make a Meta object
meta_contents = {'app_label': self.app_label, "apps": apps}
meta_contents.update(self.options)
meta = type(str("Meta"), tuple(), meta_contents)
meta = type("Meta", tuple(), meta_contents)
# Then, work out our bases
try:
bases = tuple(
@ -595,7 +595,7 @@ class ModelState:
# Restore managers
body.update(self.construct_managers())
# 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):
for fname, field in self.fields:

View File

@ -1023,7 +1023,7 @@ def create_many_to_many_intermediary_model(field, klass):
to = 'to_%s' % to
from_ = 'from_%s' % from_
meta = type(str('Meta'), (), {
meta = type('Meta', (), {
'db_table': field._get_m2m_db_table(klass._meta),
'auto_created': klass,
'app_label': klass._meta.app_label,
@ -1034,7 +1034,7 @@ def create_many_to_many_intermediary_model(field, klass):
'apps': field.model._meta.apps,
})
# Construct and return the new class.
return type(str(name), (models.Model,), {
return type(name, (models.Model,), {
'Meta': meta,
'__module__': klass.__module__,
from_: models.ForeignKey(

View File

@ -94,7 +94,7 @@ class ForwardManyToOneDescriptor:
# related model might not be resolved yet; `rel.model` might still be
# a string model reference.
return type(
str('RelatedObjectDoesNotExist'),
'RelatedObjectDoesNotExist',
(self.field.remote_field.model.DoesNotExist, AttributeError),
{}
)
@ -297,7 +297,7 @@ class ReverseOneToOneDescriptor:
# The exception isn't created at initialization time for the sake of
# consistency with `ForwardManyToOneDescriptor`.
return type(
str('RelatedObjectDoesNotExist'),
'RelatedObjectDoesNotExist',
(self.related.related_model.DoesNotExist, AttributeError),
{}
)

View File

@ -441,7 +441,7 @@ def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
'min_num': min_num, 'max_num': max_num,
'absolute_max': absolute_max, 'validate_min': validate_min,
'validate_max': validate_max}
return type(form.__name__ + str('FormSet'), (formset,), attrs)
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):

View File

@ -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
# creating needs to inherit from the parent's inner meta.
bases = (form.Meta,) if hasattr(form, 'Meta') else ()
Meta = type(str('Meta'), bases, attrs)
Meta = type('Meta', bases, attrs)
if formfield_callback:
Meta.formfield_callback = staticmethod(formfield_callback)
# 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.
form_class_attrs = {

View File

@ -197,10 +197,10 @@ class AppsTests(SimpleTestCase):
'app_label': "apps",
'apps': new_apps,
}
meta = type(str("Meta"), tuple(), meta_contents)
meta = type("Meta", tuple(), meta_contents)
body['Meta'] = meta
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!
self.assertListEqual(list(apps.get_app_config("apps").get_models()), old_models)
with self.assertRaises(LookupError):
@ -218,15 +218,15 @@ class AppsTests(SimpleTestCase):
}
body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents)
body['Meta'] = type("Meta", tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__
type(str("SouthPonies"), (models.Model,), body)
type("SouthPonies", (models.Model,), body)
# When __name__ and __module__ match we assume the module
# was reloaded and issue a warning. This use-case is
# useful for REPL. Refs #23621.
body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents)
body['Meta'] = type("Meta", tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__
msg = (
"Model 'apps.southponies' was already registered. "
@ -234,15 +234,15 @@ class AppsTests(SimpleTestCase):
"most notably with related models."
)
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
# a RuntimeError.
body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents)
body['Meta'] = type("Meta", tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__ + '.whatever'
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):
"""

View File

@ -429,7 +429,7 @@ class TestUtilsHashPass(SimpleTestCase):
self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception))
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
msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"
with self.assertRaisesRegex(ValueError, msg):

View File

@ -661,7 +661,7 @@ class RelativeFieldTests(SimpleTestCase):
pass
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),
'__module__': Parent.__module__,
})
@ -700,7 +700,7 @@ class RelativeFieldTests(SimpleTestCase):
pass
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),
'__module__': Parent.__module__,
})

View File

@ -1058,7 +1058,7 @@ class RelatedModelsTests(SimpleTestCase):
'apps': self.apps,
'proxy': proxy,
}
meta = type(str("Meta"), tuple(), meta_contents)
meta = type("Meta", tuple(), meta_contents)
if not bases:
bases = (models.Model,)
body = {

View File

@ -542,7 +542,7 @@ class WriterTests(SimpleTestCase):
'verbose_name_plural': 'My models',
}
migration = type(str("Migration"), (migrations.Migration,), {
migration = type("Migration", (migrations.Migration,), {
"operations": [
migrations.CreateModel("MyModel", tuple(fields.items()), options, (models.Model,)),
migrations.CreateModel("MyModel2", tuple(fields.items()), bases=(models.Model,)),
@ -593,7 +593,7 @@ class WriterTests(SimpleTestCase):
self.assertEqual(writer.path, expected_path)
def test_custom_operation(self):
migration = type(str("Migration"), (migrations.Migration,), {
migration = type("Migration", (migrations.Migration,), {
"operations": [
custom_migration_operations.operations.TestOperation(),
custom_migration_operations.operations.CreateModel(),
@ -615,7 +615,7 @@ class WriterTests(SimpleTestCase):
"""
#24155 - Tests ordering of imports.
"""
migration = type(str("Migration"), (migrations.Migration,), {
migration = type("Migration", (migrations.Migration,), {
"operations": [
migrations.AddField("mymodel", "myfield", models.DateTimeField(
default=datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc),
@ -635,7 +635,7 @@ class WriterTests(SimpleTestCase):
"""
Test comments at top of file.
"""
migration = type(str("Migration"), (migrations.Migration,), {
migration = type("Migration", (migrations.Migration,), {
"operations": []
})
dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc)
@ -655,7 +655,7 @@ class WriterTests(SimpleTestCase):
"""
django.db.models shouldn't be imported if unused.
"""
migration = type(str("Migration"), (migrations.Migration,), {
migration = type("Migration", (migrations.Migration,), {
"operations": [
migrations.AlterModelOptions(
name='model',

View File

@ -2731,12 +2731,12 @@ class ModelFormInheritanceTests(SimpleTestCase):
foo = forms.IntegerField()
self.assertEqual(list(ModelForm().fields.keys()), ['name'])
self.assertEqual(list(type(str('NewForm'), (Mixin, Form), {})().fields.keys()), [])
self.assertEqual(list(type(str('NewForm'), (Form2, Mixin, Form), {})().fields.keys()), ['foo'])
self.assertEqual(list(type(str('NewForm'), (Mixin, ModelForm, Form), {})().fields.keys()), ['name'])
self.assertEqual(list(type(str('NewForm'), (ModelForm, Mixin, Form), {})().fields.keys()), ['name'])
self.assertEqual(list(type(str('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', (Mixin, Form), {})().fields.keys()), [])
self.assertEqual(list(type('NewForm', (Form2, Mixin, Form), {})().fields.keys()), ['foo'])
self.assertEqual(list(type('NewForm', (Mixin, ModelForm, Form), {})().fields.keys()), ['name'])
self.assertEqual(list(type('NewForm', (ModelForm, Mixin, Form), {})().fields.keys()), ['name'])
self.assertEqual(list(type('NewForm', (ModelForm, Form, Mixin), {})().fields.keys()), ['name', 'age'])
self.assertEqual(list(type('NewForm', (ModelForm, Form), {'age': None})().fields.keys()), ['name'])
def test_field_removal_name_clashes(self):
"""

View File

@ -322,11 +322,11 @@ class AbstractInheritanceTests(TestCase):
return list((f.name, f.__class__) for f in model._meta.get_fields())
model_dict = {'__module__': 'model_inheritance'}
model1 = type(str('Model1'), (AbstractModel, Mixin), model_dict.copy())
model2 = type(str('Model2'), (Mixin2, AbstractModel), model_dict.copy())
model3 = type(str('Model3'), (DescendantMixin, AbstractModel), model_dict.copy())
model4 = type(str('Model4'), (Mixin2, Mixin, AbstractModel), model_dict.copy())
model5 = type(str('Model5'), (Mixin2, ConcreteModel2, Mixin, AbstractModel), model_dict.copy())
model1 = type('Model1', (AbstractModel, Mixin), model_dict.copy())
model2 = type('Model2', (Mixin2, AbstractModel), model_dict.copy())
model3 = type('Model3', (DescendantMixin, AbstractModel), model_dict.copy())
model4 = type('Model4', (Mixin2, Mixin, AbstractModel), model_dict.copy())
model5 = type('Model5', (Mixin2, ConcreteModel2, Mixin, AbstractModel), model_dict.copy())
self.assertEqual(
fields(model1),

View File

@ -82,8 +82,7 @@ class PickleabilityTestCase(TestCase):
def test_model_pickle_dynamic(self):
class Meta:
proxy = True
dynclass = type(str("DynamicEventSubclass"), (Event, ),
{'Meta': Meta, '__module__': Event.__module__})
dynclass = type("DynamicEventSubclass", (Event, ), {'Meta': Meta, '__module__': Event.__module__})
original = dynclass(pk=1)
dumped = pickle.dumps(original)
reloaded = pickle.loads(dumped)

View File

@ -111,7 +111,7 @@ class LiveServerPort(LiveServerBase):
Each LiveServerTestCase binds to a unique port or fails to start a
server thread when run concurrently (#26011).
"""
TestCase = type(str("TestCase"), (LiveServerBase,), {})
TestCase = type("TestCase", (LiveServerBase,), {})
try:
TestCase.setUpClass()
except socket.error as e:

View File

@ -53,7 +53,7 @@ class GetUniqueCheckTests(unittest.TestCase):
bar = models.IntegerField()
baz = models.IntegerField()
Meta = type(str('Meta'), (), {
Meta = type('Meta', (), {
'unique_together': unique_together,
'apps': Apps()
})