Skip to content

Commit

Permalink
Use a python 3.9-friendly union type syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
jieter committed Dec 21, 2024
1 parent 7b0254d commit 88f7317
Show file tree
Hide file tree
Showing 11 changed files with 47 additions and 24 deletions.
21 changes: 13 additions & 8 deletions django_tables2/columns/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import OrderedDict
from itertools import islice
from typing import Union

from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
Expand All @@ -23,7 +24,7 @@ class Library:
def __init__(self):
self.columns = []

def register(self, column):
def register(self, column: "Column"):
if not hasattr(column, "from_field"):
raise ImproperlyConfigured(f"{column.__class__.__name__} is not a subclass of Column")
self.columns.append(column)
Expand Down Expand Up @@ -68,7 +69,13 @@ class LinkTransform:
accessor = None
attrs = None

def __init__(self, url=None, accessor=None, attrs=None, reverse_args=None):
def __init__(
self,
url: Union[callable, None] = None,
accessor: Union[str, Accessor, None] = None,
attrs: Union[dict, None] = None,
reverse_args: Union[list, tuple, None] = None,
):
"""
arguments:
url (callable): If supplied, the result of this callable will be used as ``href`` attribute.
Expand All @@ -95,7 +102,7 @@ def __init__(self, url=None, accessor=None, attrs=None, reverse_args=None):

self.reverse_args = reverse_args or {}

def compose_url(self, **kwargs):
def compose_url(self, **kwargs) -> str:
if self.url and callable(self.url):
return call_with_appropriate(self.url, kwargs)

Expand All @@ -119,10 +126,8 @@ def compose_url(self, **kwargs):
)
return context.get_absolute_url()

def call_reverse(self, record):
"""
Prepares the arguments to reverse() for this record and calls reverse()
"""
def call_reverse(self, record) -> str:
"""Prepares the arguments to reverse() for this record and calls reverse()."""

def resolve_if_accessor(val):
return val.resolve(record) if isinstance(val, Accessor) else val
Expand Down Expand Up @@ -399,7 +404,7 @@ def order(self, queryset, is_descending):
return (queryset, False)

@classmethod
def from_field(cls, field, **kwargs) -> "Column | None":
def from_field(cls, field, **kwargs) -> "Union[Column, None]":
"""
Return a specialized column for the model field or `None`.
Expand Down
4 changes: 3 additions & 1 deletion django_tables2/columns/booleancolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models
from django.utils.html import escape, format_html
from django.utils.safestring import SafeString
Expand Down Expand Up @@ -58,7 +60,7 @@ def value(self, record, value, bound_column) -> str:
return str(self._get_bool_value(record, value, bound_column))

@classmethod
def from_field(cls, field, **kwargs) -> "BooleanColumn | None":
def from_field(cls, field, **kwargs) -> "Union[BooleanColumn, None]":
if isinstance(field, models.NullBooleanField):
return cls(null=True, **kwargs)

Expand Down
6 changes: 4 additions & 2 deletions django_tables2/columns/datecolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models

from .base import library
Expand All @@ -16,13 +18,13 @@ class DateColumn(TemplateColumn):
``SHORT_DATE_FORMAT`` setting, otherwise use ``DATE_FORMAT``
"""

def __init__(self, format=None, short=True, *args, **kwargs):
def __init__(self, format: Union[str, None] = None, short: bool = True, *args, **kwargs):
if format is None:
format = "SHORT_DATE_FORMAT" if short else "DATE_FORMAT"
template = '{{ value|date:"%s"|default:default }}' % format
super().__init__(template_code=template, *args, **kwargs)

@classmethod
def from_field(cls, field, **kwargs) -> "DateColumn | None":
def from_field(cls, field, **kwargs) -> "Union[DateColumn, None]":
if isinstance(field, models.DateField):
return cls(**kwargs)
6 changes: 4 additions & 2 deletions django_tables2/columns/datetimecolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models

from .base import library
Expand All @@ -16,13 +18,13 @@ class DateTimeColumn(TemplateColumn):
``SHORT_DATETIME_FORMAT``, else ``DATETIME_FORMAT``
"""

def __init__(self, format=None, short=True, *args, **kwargs):
def __init__(self, format: Union[str, None] = None, short: bool = True, *args, **kwargs):
if format is None:
format = "SHORT_DATETIME_FORMAT" if short else "DATETIME_FORMAT"
template = '{{ value|date:"%s"|default:default }}' % format
super().__init__(template_code=template, *args, **kwargs)

@classmethod
def from_field(cls, field, **kwargs) -> "DateTimeColumn | None":
def from_field(cls, field, **kwargs) -> "Union[DateTimeColumn, None]":
if isinstance(field, models.DateTimeField):
return cls(**kwargs)
4 changes: 3 additions & 1 deletion django_tables2/columns/emailcolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models

from .base import library
Expand Down Expand Up @@ -35,6 +37,6 @@ def get_url(self, value) -> str:
return f"mailto:{value}"

@classmethod
def from_field(cls, field, **kwargs) -> "EmailColumn | None":
def from_field(cls, field, **kwargs) -> "Union[EmailColumn, None]":
if isinstance(field, models.EmailField):
return cls(**kwargs)
5 changes: 3 additions & 2 deletions django_tables2/columns/filecolumn.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from typing import Union

from django.db import models
from django.utils.html import format_html
Expand Down Expand Up @@ -35,7 +36,7 @@ class FileColumn(BaseLinkColumn):
the file's ``basename`` (default)
"""

def __init__(self, verify_exists=True, **kwargs):
def __init__(self, verify_exists: bool = True, **kwargs):
self.verify_exists = verify_exists
super().__init__(**kwargs)

Expand Down Expand Up @@ -81,6 +82,6 @@ def render(self, record, value) -> SafeString:
)

@classmethod
def from_field(cls, field, **kwargs) -> "FileColumn | None":
def from_field(cls, field, **kwargs) -> "Union[FileColumn, None]":
if isinstance(field, models.FileField):
return cls(**kwargs)
3 changes: 2 additions & 1 deletion django_tables2/columns/jsoncolumn.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from typing import Union

from django.db.models import JSONField
from django.utils.html import format_html
Expand Down Expand Up @@ -47,6 +48,6 @@ def render(self, record, value) -> SafeString:
)

@classmethod
def from_field(cls, field, **kwargs) -> "JSONColumn | None":
def from_field(cls, field, **kwargs) -> "Union[JSONColumn, None]":
if isinstance(field, (JSONField, HStoreField)):
return cls(**kwargs)
4 changes: 3 additions & 1 deletion django_tables2/columns/manytomanycolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models
from django.utils.encoding import force_str
from django.utils.html import conditional_escape
Expand Down Expand Up @@ -96,6 +98,6 @@ def render(self, value) -> SafeString:
return mark_safe(conditional_escape(self.separator).join(items))

@classmethod
def from_field(cls, field, **kwargs) -> "ManyToManyColumn | None":
def from_field(cls, field, **kwargs) -> "Union[ManyToManyColumn, None]":
if isinstance(field, models.ManyToManyField):
return cls(**kwargs)
6 changes: 4 additions & 2 deletions django_tables2/columns/timecolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models

from .base import library
Expand All @@ -14,13 +16,13 @@ class TimeColumn(TemplateColumn):
short (bool): if *format* is not specified, use Django's ``TIME_FORMAT`` setting.
"""

def __init__(self, format=None, *args, **kwargs):
def __init__(self, format: Union[str, None] = None, *args, **kwargs):
if format is None:
format = "TIME_FORMAT"
template = '{{ value|date:"%s"|default:default }}' % format
super().__init__(template_code=template, *args, **kwargs)

@classmethod
def from_field(cls, field, **kwargs) -> "TimeColumn | None":
def from_field(cls, field, **kwargs) -> "Union[TimeColumn, None]":
if isinstance(field, models.TimeField):
return cls(**kwargs)
4 changes: 3 additions & 1 deletion django_tables2/columns/urlcolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.db import models

from .base import library
Expand Down Expand Up @@ -28,6 +30,6 @@ def get_url(self, value: str) -> str:
return value

@classmethod
def from_field(cls, field, **kwargs) -> "URLColumn | None":
def from_field(cls, field, **kwargs) -> "Union[URLColumn, None]":
if isinstance(field, models.URLField):
return cls(**kwargs)
8 changes: 5 additions & 3 deletions django_tables2/paginators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union

from django.core.paginator import EmptyPage, Page, PageNotAnInteger, Paginator
from django.utils.translation import gettext as _

Expand Down Expand Up @@ -62,7 +64,7 @@ def __init__(self, object_list, per_page, look_ahead=None, **kwargs):

super().__init__(object_list, per_page, **kwargs)

def validate_number(self, number: float | int) -> int:
def validate_number(self, number: Union[float, int]) -> int:
"""Validate the given 1-based page number."""
try:
if isinstance(number, float) and not number.is_integer():
Expand All @@ -74,7 +76,7 @@ def validate_number(self, number: float | int) -> int:
raise EmptyPage(_("That page number is less than 1"))
return number

def page(self, number: float | int) -> Page:
def page(self, number: Union[float, int]) -> Page:
# Number might be None, because the total number of pages is not known in this paginator.
# If an unknown page is requested, serve the first page.
number = self.validate_number(number or 1)
Expand All @@ -98,7 +100,7 @@ def page(self, number: float | int) -> Page:
self._final_num_pages = number
return Page(objects, number, self)

def is_last_page(self, number: float | int) -> bool:
def is_last_page(self, number: Union[float, int]) -> bool:
return number == self._final_num_pages

def _get_count(self):
Expand Down

0 comments on commit 88f7317

Please sign in to comment.