MCPcopy Index your code
hub / github.com/python/cpython / __new__

Method __new__

Lib/_pydatetime.py:646–757  ·  view source on GitHub ↗
(cls, days=0, seconds=0, microseconds=0,
                milliseconds=0, minutes=0, hours=0, weeks=0)

Source from the content-addressed store, hash-verified

644 __slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
645
646 def __new__(cls, days=0, seconds=0, microseconds=0,
647 milliseconds=0, minutes=0, hours=0, weeks=0):
648 # Doing this efficiently and accurately in C is going to be difficult
649 # and error-prone, due to ubiquitous overflow possibilities, and that
650 # C double doesn't have enough bits of precision to represent
651 # microseconds over 10K years faithfully. The code here tries to make
652 # explicit where go-fast assumptions can be relied on, in order to
653 # guide the C implementation; it's way more convoluted than speed-
654 # ignoring auto-overflow-to-long idiomatic Python could be.
655
656 for name, value in (
657 ("days", days),
658 ("seconds", seconds),
659 ("microseconds", microseconds),
660 ("milliseconds", milliseconds),
661 ("minutes", minutes),
662 ("hours", hours),
663 ("weeks", weeks)
664 ):
665 if not isinstance(value, (int, float)):
666 raise TypeError(
667 f"unsupported type for timedelta {name} component: {type(value).__name__}"
668 )
669
670 # Final values, all integer.
671 # s and us fit in 32-bit signed ints; d isn't bounded.
672 d = s = us = 0
673
674 # Normalize everything to days, seconds, microseconds.
675 days += weeks*7
676 seconds += minutes*60 + hours*3600
677 microseconds += milliseconds*1000
678
679 # Get rid of all fractions, and normalize s and us.
680 # Take a deep breath <wink>.
681 if isinstance(days, float):
682 dayfrac, days = _math.modf(days)
683 daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
684 assert daysecondswhole == int(daysecondswhole) # can't overflow
685 s = int(daysecondswhole)
686 assert days == int(days)
687 d = int(days)
688 else:
689 daysecondsfrac = 0.0
690 d = days
691 assert isinstance(daysecondsfrac, float)
692 assert abs(daysecondsfrac) <= 1.0
693 assert isinstance(d, int)
694 assert abs(s) <= 24 * 3600
695 # days isn't referenced again before redefinition
696
697 if isinstance(seconds, float):
698 secondsfrac, seconds = _math.modf(seconds)
699 assert seconds == int(seconds)
700 seconds = int(seconds)
701 secondsfrac += daysecondsfrac
702 assert abs(secondsfrac) <= 2.0
703 else:

Callers

nothing calls this directly

Calls 2

absFunction · 0.85
__new__Method · 0.45

Tested by

no test coverage detected