Skip to content

Commit

Permalink
Merge pull request #523 from claudep/cleanup
Browse files Browse the repository at this point in the history
Applied some more Python 2 cleanup
  • Loading branch information
benjaoming committed Oct 27, 2019
2 parents bcd691f + a8cc805 commit a8df354
Show file tree
Hide file tree
Showing 22 changed files with 37 additions and 70 deletions.
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ This version adds tests, and comes with several critical bugfixes.

Django versions supported: 1.11, 2.1, 2.2

Python versions supported: 2.7, 3.5, 3.6, 3.7
Python versions supported: 3.5, 3.6, 3.7

PyPy versions supported: PyPy 2.6, PyPy3 2.4
PyPy versions supported: PyPy3 2.4

If you need support for older versions of Django and Python you can use the latest version in 0.11.x branch.

Expand Down
10 changes: 5 additions & 5 deletions djmoney/contrib/django_rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class MoneyField(DecimalField):

def __init__(self, *args, **kwargs):
self.default_currency = kwargs.pop("default_currency", None)
super(MoneyField, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# Rest Framework converts `min_value` / `max_value` to validators, that are not aware about `Money` class
# We need to adjust them
for idx, validator in enumerate(self.validators):
Expand All @@ -33,16 +33,16 @@ def to_representation(self, obj):
"""
if isinstance(obj, MONEY_CLASSES):
obj = obj.amount
return super(MoneyField, self).to_representation(obj)
return super().to_representation(obj)

def to_internal_value(self, data):
if isinstance(data, MONEY_CLASSES):
amount = super(MoneyField, self).to_internal_value(data.amount)
amount = super().to_internal_value(data.amount)
return Money(amount, data.currency)
return super(MoneyField, self).to_internal_value(data)
return super().to_internal_value(data)

def get_value(self, data):
amount = super(MoneyField, self).get_value(data)
amount = super().get_value(data)
currency = data.get(get_currency_field_name(self.field_name), self.default_currency)
if currency and amount is not None and not isinstance(amount, MONEY_CLASSES) and amount is not empty:
return Money(amount, currency)
Expand Down
2 changes: 1 addition & 1 deletion djmoney/contrib/exchange/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
raise ImportError("Please install dependency certifi - pip install certifi")


class BaseExchangeBackend(object):
class BaseExchangeBackend:
name = None
url = None

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Command(BaseExchangeCommand):
help = "Clears exchange rates."

def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
super().add_arguments(parser)
parser.add_argument(
"--all",
action="store_true",
Expand Down
4 changes: 2 additions & 2 deletions djmoney/forms/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(
)
# The two fields that this widget comprises
fields = (amount_field, currency_field)
super(MoneyField, self).__init__(fields, *args, **kwargs)
super().__init__(fields, *args, **kwargs)

# set the initial value to the default currency so that the
# default currency appears as the selected menu item
Expand All @@ -60,7 +60,7 @@ def compress(self, data_list):
def clean(self, value):
if isinstance(value, MONEY_CLASSES):
value = (value.amount, value.currency)
return super(MoneyField, self).clean(value)
return super().clean(value)

def has_changed(self, initial, data): # noqa
if self.disabled:
Expand Down
2 changes: 1 addition & 1 deletion djmoney/forms/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(
if not currency_widget:
currency_widget = Select(choices=choices)
widgets = (amount_widget, currency_widget)
super(MoneyWidget, self).__init__(widgets, *args, **kwargs)
super().__init__(widgets, *args, **kwargs)

def decompress(self, value):
if value is not None:
Expand Down
22 changes: 11 additions & 11 deletions djmoney/models/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

class MoneyValidator(DecimalValidator):
def __call__(self, value):
return super(MoneyValidator, self).__call__(value.amount)
return super().__call__(value.amount)


def get_value(obj, expr):
Expand Down Expand Up @@ -81,7 +81,7 @@ def get_currency(value):
return value[1]


class MoneyFieldProxy(object):
class MoneyFieldProxy:
def __init__(self, field):
self.field = field
self.currency_field_name = get_currency_field_name(self.field.name, self.field)
Expand Down Expand Up @@ -151,11 +151,11 @@ def __init__(self, price_field=None, default=DEFAULT_CURRENCY, **kwargs):
default = default.code
kwargs.setdefault("max_length", 3)
self.price_field = price_field
super(CurrencyField, self).__init__(default=default, **kwargs)
super().__init__(default=default, **kwargs)

def contribute_to_class(self, cls, name):
if name not in [f.name for f in cls._meta.fields]:
super(CurrencyField, self).contribute_to_class(cls, name)
super().contribute_to_class(cls, name)


class MoneyField(models.DecimalField):
Expand Down Expand Up @@ -186,7 +186,7 @@ def __init__(
self.currency_field_name = currency_field_name
self.money_descriptor_class = money_descriptor_class

super(MoneyField, self).__init__(verbose_name, name, max_digits, decimal_places, default=default, **kwargs)
super().__init__(verbose_name, name, max_digits, decimal_places, default=default, **kwargs)
self.creation_counter += 1
Field.creation_counter += 1

Expand Down Expand Up @@ -218,7 +218,7 @@ def to_python(self, value):
value = value[0]
if isinstance(value, float):
value = str(value)
return super(MoneyField, self).to_python(value)
return super().to_python(value)

def clean(self, value, model_instance):
"""
Expand All @@ -242,7 +242,7 @@ def contribute_to_class(self, cls, name):
if not hasattr(self, "_currency_field"):
self.add_currency_field(cls, name)

super(MoneyField, self).contribute_to_class(cls, name)
super().contribute_to_class(cls, name)

setattr(cls, self.name, self.money_descriptor_class(self))

Expand All @@ -266,13 +266,13 @@ def add_currency_field(self, cls, name):
def get_db_prep_save(self, value, connection):
if isinstance(value, MONEY_CLASSES):
value = value.amount
return super(MoneyField, self).get_db_prep_save(value, connection)
return super().get_db_prep_save(value, connection)

def get_default(self):
if isinstance(self.default, Money):
return self.default
else:
return super(MoneyField, self).get_default()
return super().get_default()

def formfield(self, **kwargs):
defaults = {"form_class": forms.MoneyField, "decimal_places": DECIMAL_PLACES}
Expand All @@ -281,14 +281,14 @@ def formfield(self, **kwargs):
defaults["default_currency"] = self.default_currency
if self.default is not None:
defaults["default_amount"] = self.default.amount
return super(MoneyField, self).formfield(**defaults)
return super().formfield(**defaults)

def value_to_string(self, obj):
value = self.value_from_object(obj)
return self.get_prep_value(value)

def deconstruct(self):
name, path, args, kwargs = super(MoneyField, self).deconstruct()
name, path, args, kwargs = super().deconstruct()

if self.default is None:
del kwargs["default"]
Expand Down
2 changes: 1 addition & 1 deletion djmoney/models/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def money_manager(manager):
# are tricky to get to the bottom of - Manager does funny things.
class MoneyManager(manager.__class__):
def get_queryset(self, *args, **kwargs):
queryset = super(MoneyManager, self).get_queryset(*args, **kwargs)
queryset = super().get_queryset(*args, **kwargs)
return add_money_comprehension_to_queryset(queryset)

manager.__class__ = MoneyManager
Expand Down
2 changes: 1 addition & 1 deletion djmoney/models/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from django.core.exceptions import ValidationError
from django.core.validators import BaseValidator
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _

from djmoney.money import Money

Expand Down
20 changes: 7 additions & 13 deletions djmoney/money.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,37 +24,37 @@ class Money(DefaultMoney):

def __init__(self, *args, **kwargs):
self.decimal_places = kwargs.pop("decimal_places", DECIMAL_PLACES)
super(Money, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def __add__(self, other):
if isinstance(other, F):
return other.__radd__(self)
other = maybe_convert(other, self.currency)
return super(Money, self).__add__(other)
return super().__add__(other)

def __sub__(self, other):
if isinstance(other, F):
return other.__rsub__(self)
other = maybe_convert(other, self.currency)
return super(Money, self).__sub__(other)
return super().__sub__(other)

def __mul__(self, other):
if isinstance(other, F):
return other.__rmul__(self)
return super(Money, self).__mul__(other)
return super().__mul__(other)

def __truediv__(self, other):
if isinstance(other, F):
return other.__rtruediv__(self)
return super(Money, self).__truediv__(other)
return super().__truediv__(other)

@property
def is_localized(self):
if self.use_l10n is None:
return settings.USE_L10N
return self.use_l10n

def __unicode__(self):
def __str__(self):
kwargs = {"money": self, "decimal_places": self.decimal_places}
if self.is_localized:
locale = get_current_locale()
Expand All @@ -63,14 +63,8 @@ def __unicode__(self):

return format_money(**kwargs)

def __str__(self):
value = self.__unicode__()
if not isinstance(value, str):
value = value.encode("utf8")
return value

def __html__(self):
return mark_safe(avoid_wrapping(conditional_escape(self.__unicode__())))
return mark_safe(avoid_wrapping(conditional_escape(str(self))))

def __round__(self, n=None):
amount = round(self.amount, n)
Expand Down
4 changes: 0 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def run_tests(self):


test_requirements = [
'mock',
'pytest>=3.1.0',
'pytest-django',
'pytest-pythonpath',
Expand All @@ -40,9 +39,6 @@ def run_tests(self):
}


if sys.version_info[0] == 2:
test_requirements.append('mock')

setup(
name='django-money',
version=djmoney.__version__,
Expand Down
6 changes: 0 additions & 6 deletions tests/_compat.py

This file was deleted.

2 changes: 1 addition & 1 deletion tests/contrib/exchange/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
from contextlib import contextmanager
from decimal import Decimal
from unittest.mock import Mock, patch

from django.core.cache import cache

Expand All @@ -9,7 +10,6 @@
from djmoney.contrib.exchange.backends import FixerBackend, OpenExchangeRatesBackend
from djmoney.contrib.exchange.backends.base import BaseExchangeBackend
from djmoney.contrib.exchange.models import ExchangeBackend, Rate
from tests._compat import Mock, patch


pytestmarks = pytest.mark.django_db
Expand Down
2 changes: 1 addition & 1 deletion tests/contrib/exchange/test_model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from decimal import Decimal
from textwrap import dedent
from unittest.mock import patch

from django.core.exceptions import ImproperlyConfigured

Expand All @@ -8,7 +9,6 @@
from djmoney.contrib.exchange.exceptions import MissingRate
from djmoney.contrib.exchange.models import _get_rate, convert_money, get_rate
from djmoney.money import Currency, Money
from tests._compat import patch


pytestmark = pytest.mark.django_db
Expand Down
2 changes: 1 addition & 1 deletion tests/contrib/test_django_rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __new__(cls, name, bases, attrs):

if field_name is not None and field_kwargs is not None:
attrs[field_name] = MoneyField(max_digits=10, decimal_places=2, **field_kwargs)
return super(MetaSerializer, cls).__new__(cls, name, bases, attrs)
return super().__new__(cls, name, bases, attrs)

class Serializer(serializers.ModelSerializer, metaclass=MetaSerializer):
class Meta:
Expand Down
2 changes: 0 additions & 2 deletions tests/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

import warnings
from decimal import ROUND_HALF_EVEN

Expand Down
2 changes: 0 additions & 2 deletions tests/test_admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

import django.contrib.admin.utils as admin_utils

import pytest
Expand Down
9 changes: 1 addition & 8 deletions tests/test_money.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import sys

from django.utils.translation import override

import pytest
Expand All @@ -17,7 +15,7 @@ def test_html_safe():

def test_html_unsafe():
class UnsafeMoney(Money):
def __unicode__(self):
def __str__(self):
return "<script>"

assert UnsafeMoney().__html__() == "&lt;script&gt;"
Expand All @@ -27,7 +25,6 @@ def test_default_mul():
assert Money(10, "USD") * 2 == Money(20, "USD")


@pytest.mark.skipif(sys.version_info[0] == 2, reason="py-moneyed doesnt support division on Python 2")
def test_default_truediv():
assert Money(10, "USD") / 2 == Money(5, "USD")

Expand All @@ -38,10 +35,6 @@ def test_get_current_locale(locale, expected):
assert get_current_locale() == expected


@pytest.mark.skipif(
sys.version_info[0] == 2,
reason="round uses float on Python 2, which is a deprecated conversion for Money instances",
)
def test_round():
assert round(Money("1.69", "USD"), 1) == Money("1.7", "USD")

Expand Down
2 changes: 1 addition & 1 deletion tests/test_serialization.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from unittest.mock import patch

from django.core.management import call_command
from django.core.serializers.base import DeserializationError
Expand All @@ -8,7 +9,6 @@
from djmoney.money import Money
from djmoney.serializers import Deserializer, Serializer

from ._compat import patch
from .testapp.models import ModelWithDefaultAsInt


Expand Down
2 changes: 0 additions & 2 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

from importlib import reload as reload_module

from django.db import models
Expand Down
2 changes: 0 additions & 2 deletions tests/test_tags.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

from django.template import Context, Template, TemplateSyntaxError
from django.utils.translation import override

Expand Down

0 comments on commit a8df354

Please sign in to comment.