[issue20861] datetime argument handling inconsistent; should accept logical integers, not coercible values

Josh Rosenberg report at bugs.python.org
Fri Mar 7 00:46:53 CET 2014


New submission from Josh Rosenberg:

Per my comments on #20858, datetime's argument handling is inconsistent. By using the 'i' format code, non-integer types are being coerced to int, even as other equivalent non-integer types are accepted (sometimes in a lossy fashion).

Example:

    >>> from decimal import Decimal as d
    >>> from datetime import datetime
    >>> datetime(d("2000.5"), 1, 2)
    datetime.datetime(2000, 1, 2, 0, 0)
    >>> datetime(2000.0, 1, 2)
    Traceback (most recent call last):
       ...
    TypeError: integer argument expected, got float

Note that the latter case would not lose data by coercion to int, yet it raises an error anyway, while the former is losing data silently.

Similar discrepancies would occur between passing a str argument vs. a user-defined string type (the latter would need to implement __int__ to get the coercion that str gets through a special case in the int constructor, making int(x) and x.__int__() subtly different, since there is no str.__int__).

For consistency, it seems like we should primarily be using typecode 'n', not 'i', so logical integers are properly converted, while anything else (including float/Decimal/str/user-string) must be cast by the caller to avoid the risk of silent data loss.

I suspect tons of modules make similar "mistakes" in the interface (until today, I didn't realize PyLong_AsLong, and by extension, the 'i' type code would coerce non-integral types). I'm looking to start contributing to Python, and at least for time being I think I'll keep the bug targeted.

I haven't tested, but I suspect this bug is in all versions of Python. Clearly it's not a bug or security issue worth a backport prior to 3.4 though.

I'd happily create and submit a patch if this is a desired fix; I'd appreciate any pointers on how to get started (to date, all my Python C extension development has been for organization internal modules).

----------
components: Extension Modules, Library (Lib)
messages: 212853
nosy: ShadowRanger
priority: normal
severity: normal
status: open
title: datetime argument handling inconsistent; should accept logical integers, not coercible values
type: behavior
versions: Python 3.4, Python 3.5

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20861>
_______________________________________


More information about the Python-bugs-list mailing list