Skip to content

Commit

Permalink
Update typing comments and add py.typed for PEP-561 compliance
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanforbes committed Nov 30, 2018
1 parent 19d43e8 commit 77f9561
Show file tree
Hide file tree
Showing 18 changed files with 187 additions and 121 deletions.
24 changes: 11 additions & 13 deletions pendulum/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import absolute_import

import datetime as _datetime
from typing import Union
from typing import Union, Optional

from .__version__ import __version__

Expand Down Expand Up @@ -59,7 +59,7 @@
SECONDS_PER_DAY,
)

_TEST_NOW = None
_TEST_NOW = None # type: Optional[DateTime]
_LOCALE = "en"
_WEEK_STARTS_AT = MONDAY
_WEEK_ENDS_AT = SUNDAY
Expand All @@ -68,7 +68,7 @@


def _safe_timezone(obj):
# type: (Union[str, int, float, _datetime.tzinfo]) -> _Timezone
# type: (Optional[Union[str, float, _datetime.tzinfo, _Timezone]]) -> _Timezone
"""
Creates a timezone instance
from a string, Timezone, TimezoneInfo or integer offset.
Expand Down Expand Up @@ -105,7 +105,7 @@ def datetime(
minute=0, # type: int
second=0, # type: int
microsecond=0, # type: int
tz=UTC, # type: Union[str, _Timezone]
tz=UTC, # type: Optional[Union[str, float, _Timezone]]
dst_rule=POST_TRANSITION, # type: str
): # type: (...) -> DateTime
"""
Expand Down Expand Up @@ -169,8 +169,8 @@ def time(hour, minute=0, second=0, microsecond=0): # type: (int, int, int, int)


def instance(
dt, tz=UTC # type: _datetime.datetime # type: Union[str, _Timezone, None]
): # type: (...) -> DateTime
dt, tz=UTC
): # type: (_datetime.datetime, Optional[Union[str, _Timezone]]) -> DateTime
"""
Create a DateTime instance from a datetime one.
"""
Expand Down Expand Up @@ -198,7 +198,7 @@ def instance(
)


def now(tz=None): # type: (Union[str, _Timezone, None]) -> DateTime
def now(tz=None): # type: (Optional[Union[str, _Timezone]]) -> DateTime
"""
Get a DateTime instance for the current date and time.
"""
Expand Down Expand Up @@ -248,7 +248,7 @@ def from_format(
string, # type: str
fmt, # type: str
tz=UTC, # type: Union[str, _Timezone]
locale=None, # type: Union[str, None]
locale=None, # type: Optional[str]
): # type: (...) -> DateTime
"""
Creates a DateTime instance from a specific format.
Expand All @@ -261,8 +261,8 @@ def from_format(


def from_timestamp(
timestamp, tz=UTC # type: Union[int, float] # type: Union[str, _Timezone]
): # type: (...) -> DateTime
timestamp, tz=UTC
): # type: (Union[int, float], Union[str, _Timezone]) -> DateTime
"""
Create a DateTime instance from a timestamp.
"""
Expand Down Expand Up @@ -305,9 +305,7 @@ def duration(
)


def period(
start, end, absolute=False # type: DateTime # type: DateTime # type: bool
): # type: (...) -> Period
def period(start, end, absolute=False): # type: (DateTime, DateTime, bool) -> Period
"""
Create a Period instance.
"""
Expand Down
21 changes: 13 additions & 8 deletions pendulum/_extensions/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from collections import namedtuple

import datetime
import typing

from ..constants import (
EPOCH_YEAR,
Expand Down Expand Up @@ -48,18 +49,18 @@ def __repr__(self):
)


def is_leap(year):
def is_leap(year): # type: (int) -> bool
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


def is_long_year(year):
def is_long_year(year): # type: (int) -> bool
def p(y):
return y + y // 4 - y // 100 + y // 400

return p(year) % 7 == 4 or p(year - 1) % 7 == 3


def week_day(year, month, day):
def week_day(year, month, day): # type: (int, int, int) -> int
if month < 3:
year -= 1

Expand All @@ -78,14 +79,14 @@ def week_day(year, month, day):
return w


def days_in_year(year):
def days_in_year(year): # type: (int) -> int
if is_leap(year):
return DAYS_PER_L_YEAR

return DAYS_PER_N_YEAR


def timestamp(dt): # type: (datetime) -> int
def timestamp(dt): # type: (datetime.datetime) -> int
year = dt.year

result = (year - 1970) * 365 + MONTHS_OFFSETS[0][dt.month]
Expand All @@ -107,7 +108,9 @@ def timestamp(dt): # type: (datetime) -> int
return result


def local_time(unix_time, utc_offset, microseconds):
def local_time(
unix_time, utc_offset, microseconds
): # type: (int, int, int) -> typing.Tuple[int, int, int, int, int, int, int]
"""
Returns a UNIX time as a broken down time
for a particular transition type.
Expand Down Expand Up @@ -182,7 +185,9 @@ def local_time(unix_time, utc_offset, microseconds):
return (year, month, day, hour, minute, second, microseconds)


def precise_diff(d1, d2):
def precise_diff(
d1, d2
): # type: (typing.Union[datetime.datetime, datetime.date], typing.Union[datetime.datetime, datetime.date]) -> PreciseDiff
"""
Calculate a precise difference between two datetimes.
Expand Down Expand Up @@ -341,7 +346,7 @@ def precise_diff(d1, d2):
)


def _day_number(year, month, day):
def _day_number(year, month, day): # type: (int, int, int) -> int
month = (month + 9) % 12
year = year - month // 10

Expand Down
26 changes: 15 additions & 11 deletions pendulum/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import datetime
import pendulum

from typing import Union
from typing import Union, Optional, TypeVar

from .date import Date
from .time import Time
Expand Down Expand Up @@ -37,9 +37,13 @@
W3C,
)

_D = TypeVar("_D", bound="DateTime")


class DateTime(datetime.datetime, Date):

EPOCH = None # type: DateTime

# Formats

_FORMATS = {
Expand Down Expand Up @@ -93,7 +97,7 @@ def __new__(
return self

@classmethod
def now(cls, tz=None): # type: (Union[str, Timezone, None]) -> DateTime
def now(cls, tz=None): # type: (Optional[Union[str, Timezone]]) -> DateTime
"""
Get a DateTime instance for the current date and time.
"""
Expand Down Expand Up @@ -214,21 +218,21 @@ def offset_hours(self):
return self.get_offset() / SECONDS_PER_MINUTE / MINUTES_PER_HOUR

@property
def timezone(self): # type: () -> Union[str, None]
def timezone(self): # type: () -> Optional[Timezone]
if not isinstance(self.tzinfo, Timezone):
return

return self.tzinfo

@property
def tz(self): # type: () -> Union[str, None]
def tz(self): # type: () -> Optional[Timezone]
return self.timezone

@property
def timezone_name(self): # type: () -> Union[str, None]
def timezone_name(self): # type: () -> Optional[str]
tz = self.timezone

if self.timezone is None:
if tz is None:
return None

return tz.name
Expand All @@ -255,7 +259,7 @@ def date(self):
def time(self):
return Time(self.hour, self.minute, self.second, self.microsecond)

def naive(self): # type: () -> DateTime
def naive(self): # type: (_D) -> _D
"""
Return the DateTime without timezone information.
"""
Expand Down Expand Up @@ -597,7 +601,7 @@ def add(
minutes=0,
seconds=0,
microseconds=0,
): # type: (int, int, int, int, int, int, int) -> DateTime
): # type: (_D, int, int, int, int, int, int, int, int) -> _D
"""
Add a duration to the instance.
Expand Down Expand Up @@ -794,10 +798,10 @@ def diff(self, dt=None, abs=True):

def diff_for_humans(
self,
other=None, # type: Union['DateTime', None]
other=None, # type: Optional[DateTime]
absolute=False, # type: bool
locale=None, # type:Union[str, None]
): # type: (...) -> False
locale=None, # type: Optional[str]
): # type: (...) -> str
"""
Get the difference in a human readable format in the current locale.
Expand Down
7 changes: 6 additions & 1 deletion pendulum/formatting/difference_formatter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from pendulum.utils._compat import decode

from ..locales.locale import Locale
from ..period import Period

import typing


class DifferenceFormatter(object):
Expand All @@ -11,7 +14,9 @@ class DifferenceFormatter(object):
def __init__(self, locale="en"):
self._locale = Locale.load(locale)

def format(self, diff, is_now=True, absolute=False, locale=None):
def format(
self, diff, is_now=True, absolute=False, locale=None
): # type: (Period, bool, bool, typing.Optional[str]) -> str
"""
Formats a difference.
Expand Down
26 changes: 17 additions & 9 deletions pendulum/formatting/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,9 @@ class Formatter:
"z": str,
}

def format(self, dt, fmt, locale=None):
def format(
self, dt, fmt, locale=None
): # type: (pendulum.DateTime, str, typing.Optional[typing.Union[str, Locale]]) -> str
"""
Formats a DateTime instance with a given format and locale.
Expand Down Expand Up @@ -260,7 +262,9 @@ def format(self, dt, fmt, locale=None):

return decode(result)

def _format_token(self, dt, token, locale):
def _format_token(
self, dt, token, locale
): # type: (pendulum.DateTime, str, Locale) -> str
"""
Formats a DateTime instance with a given token and locale.
Expand Down Expand Up @@ -306,7 +310,9 @@ def _format_token(self, dt, token, locale):

return "{}{:02d}{}{:02d}".format(sign, hour, separator, minute)

def _format_localizable_token(self, dt, token, locale):
def _format_localizable_token(
self, dt, token, locale
): # type: (pendulum.DateTime, str, Locale) -> str
"""
Formats a DateTime instance
with a given localizable token and locale.
Expand Down Expand Up @@ -360,8 +366,8 @@ def parse(
time, # type: str
fmt, # type: str
now, # type: pendulum.DateTime
locale=None, # type: typing.Union[str, None]
): # type: (...) -> dict
locale=None, # type: typing.Optional[str]
): # type: (...) -> typing.Dict[str, typing.Any]
"""
Parses a time string matching a given format as a tuple.
Expand Down Expand Up @@ -410,7 +416,9 @@ def parse(

return self._check_parsed(parsed, now)

def _check_parsed(self, parsed, now): # type: (dict, pendulum.DateTime) -> dict
def _check_parsed(
self, parsed, now
): # type: (typing.Dict[str, typing.Any], pendulum.DateTime) -> typing.Dict[str, typing.Any]
"""
Checks validity of parsed elements.
Expand Down Expand Up @@ -530,7 +538,7 @@ def _check_parsed(self, parsed, now): # type: (dict, pendulum.DateTime) -> dict

def _get_parsed_values(
self, m, parsed, locale, now
): # type: (..., dict, Locale, pendulum.DateTime) -> None
): # type: (typing.Match[str], typing.Dict[str, typing.Any], Locale, pendulum.DateTime) -> None
for token, index in m.re.groupindex.items():
if token in self._LOCALIZABLE_TOKENS:
self._get_parsed_locale_value(token, m.group(index), parsed, locale)
Expand All @@ -539,7 +547,7 @@ def _get_parsed_values(

def _get_parsed_value(
self, token, value, parsed, now
): # type: (str, str, dict, pendulum.DateTime) -> None
): # type: (str, str, typing.Dict[str, typing.Any], pendulum.DateTime) -> None
parsed_token = self._PARSE_TOKENS[token](value)

if "Y" in token:
Expand Down Expand Up @@ -599,7 +607,7 @@ def _get_parsed_value(

def _get_parsed_locale_value(
self, token, value, parsed, locale
): # type: (str, str, dict, Locale) -> None
): # type: (str, str, typing.Dict[str, typing.Any], Locale) -> None
if token == "MMMM":
unit = "month"
match = "months.wide"
Expand Down
Loading

0 comments on commit 77f9561

Please sign in to comment.