index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
148
arpeggio
ParsingExpression
An abstract class for all parsing expressions. Represents the node of the Parser Model. Attributes: elements: A list (or other python object) used as a staging structure for python based grammar definition. Used in _from_python for building nodes list of child parser expressions. rule_name (str): The name of the parser rule if this is the root rule. root (bool): Does this parser expression represents the root of the parser rule? The root parser rule will create non-terminal node of the parse tree during parsing. nodes (list of ParsingExpression): A list of child parser expressions. suppress (bool): If this is set to True than no ParseTreeNode will be created for this ParsingExpression. Default False.
class ParsingExpression(object): """ An abstract class for all parsing expressions. Represents the node of the Parser Model. Attributes: elements: A list (or other python object) used as a staging structure for python based grammar definition. Used in _from_python for building nodes list of child parser expressions. rule_name (str): The name of the parser rule if this is the root rule. root (bool): Does this parser expression represents the root of the parser rule? The root parser rule will create non-terminal node of the parse tree during parsing. nodes (list of ParsingExpression): A list of child parser expressions. suppress (bool): If this is set to True than no ParseTreeNode will be created for this ParsingExpression. Default False. """ suppress = False def __init__(self, *elements, **kwargs): if len(elements) == 1: elements = elements[0] self.elements = elements self.rule_name = kwargs.get('rule_name', '') self.root = kwargs.get('root', False) nodes = kwargs.get('nodes', []) if not hasattr(nodes, '__iter__'): nodes = [nodes] self.nodes = nodes if 'suppress' in kwargs: self.suppress = kwargs['suppress'] # Memoization. Every node cache the parsing results for the given input # positions. self._result_cache = {} # position -> parse tree at the position @property def desc(self): return "{}{}".format(self.name, "-" if self.suppress else "") @property def name(self): if self.root: return "%s=%s" % (self.rule_name, self.__class__.__name__) else: return self.__class__.__name__ @property def id(self): if self.root: return self.rule_name else: return id(self) def _clear_cache(self, processed=None): """ Clears memoization cache. Should be called on input change and end of parsing. Args: processed (set): Set of processed nodes to prevent infinite loops. """ self._result_cache = {} if not processed: processed = set() for node in self.nodes: if node not in processed: processed.add(node) node._clear_cache(processed) def parse(self, parser): if parser.debug: name = self.name if name.startswith('__asgn'): name = "{}[{}]".format(self.name, self._attr_name) parser.dprint(">> Matching rule {}{} at position {} => {}" .format(name, " in {}".format(parser.in_rule) if parser.in_rule else "", parser.position, parser.context()), 1) # Current position could change in recursive calls # so save it. c_pos = parser.position # Memoization. # If this position is already parsed by this parser expression use # the result if parser.memoization: try: result, new_pos = self._result_cache[c_pos] parser.position = new_pos parser.cache_hits += 1 if parser.debug: parser.dprint( "** Cache hit for [{}, {}] = '{}' : new_pos={}" .format(name, c_pos, text(result), text(new_pos))) parser.dprint( "<<+ Matched rule {} at position {}" .format(name, new_pos), -1) # If NoMatch is recorded at this position raise. if result is NOMATCH_MARKER: raise parser.nm # else return cached result return result except KeyError: parser.cache_misses += 1 # Remember last parsing expression and set this as # the new last. last_pexpression = parser.last_pexpression parser.last_pexpression = self if self.rule_name: # If we are entering root rule # remember previous root rule name and set # this one on the parser to be available for # debugging messages previous_root_rule_name = parser.in_rule parser.in_rule = self.rule_name try: result = self._parse(parser) if self.suppress or (type(result) is list and result and result[0] is None): result = None except NoMatch: parser.position = c_pos # Backtracking # Memoize NoMatch at this position for this rule if parser.memoization: self._result_cache[c_pos] = (NOMATCH_MARKER, c_pos) raise finally: # Recover last parsing expression. parser.last_pexpression = last_pexpression if parser.debug: parser.dprint("<<{} rule {}{} at position {} => {}" .format("- Not matched" if parser.position is c_pos else "+ Matched", name, " in {}".format(parser.in_rule) if parser.in_rule else "", parser.position, parser.context()), -1) # If leaving root rule restore previous root rule name. if self.rule_name: parser.in_rule = previous_root_rule_name # For root rules flatten non-terminal/list if self.root and result and not isinstance(result, Terminal): if not isinstance(result, NonTerminal): result = flatten(result) # Tree reduction will eliminate Non-terminal with single child. if parser.reduce_tree and len(result) == 1: result = result[0] # If the result is not parse tree node it must be a plain list # so create a new NonTerminal. if not isinstance(result, ParseTreeNode): result = NonTerminal(self, result) # Result caching for use by memoization. if parser.memoization: self._result_cache[c_pos] = (result, parser.position) return result
(*elements, **kwargs)
152
arpeggio
RegExMatch
This Match class will perform input matching based on Regular Expressions. Args: to_match (regex string): A regular expression string to match. It will be used to create regular expression using re.compile. ignore_case(bool): If case insensitive match is needed. Default is None to support propagation from global parser setting. multiline(bool): allow regex to works on multiple lines (re.DOTALL flag). Default is None to support propagation from global parser setting. str_repr(str): A string that is used to represent this regex. re_flags: flags parameter for re.compile if neither ignore_case or multiple are set.
class RegExMatch(Match): ''' This Match class will perform input matching based on Regular Expressions. Args: to_match (regex string): A regular expression string to match. It will be used to create regular expression using re.compile. ignore_case(bool): If case insensitive match is needed. Default is None to support propagation from global parser setting. multiline(bool): allow regex to works on multiple lines (re.DOTALL flag). Default is None to support propagation from global parser setting. str_repr(str): A string that is used to represent this regex. re_flags: flags parameter for re.compile if neither ignore_case or multiple are set. ''' def __init__(self, to_match, rule_name='', root=False, ignore_case=None, multiline=None, str_repr=None, re_flags=re.MULTILINE, **kwargs): super(RegExMatch, self).__init__(rule_name, root, **kwargs) self.to_match_regex = to_match self.ignore_case = ignore_case self.multiline = multiline self.explicit_flags = re_flags self.to_match = str_repr if str_repr is not None else to_match def compile(self): flags = self.explicit_flags if self.multiline is True: flags |= re.DOTALL if self.multiline is False and flags & re.DOTALL: flags -= re.DOTALL if self.ignore_case is True: flags |= re.IGNORECASE if self.ignore_case is False and flags & re.IGNORECASE: flags -= re.IGNORECASE self.regex = re.compile(self.to_match_regex, flags) def __str__(self): return self.to_match def __unicode__(self): return self.__str__() def _parse(self, parser): c_pos = parser.position m = self.regex.match(parser.input, c_pos) if m: matched = m.group() if parser.debug: parser.dprint( "++ Match '%s' at %d => '%s'" % (matched, c_pos, parser.context(len(matched)))) parser.position += len(matched) if matched: return Terminal(self, c_pos, matched, extra_info=m) else: if parser.debug: parser.dprint("-- NoMatch at {}".format(c_pos)) parser._nm_raise(self, c_pos, parser)
(to_match, rule_name='', root=False, ignore_case=None, multiline=None, str_repr=None, re_flags=re.MULTILINE, **kwargs)
153
arpeggio
__init__
null
def __init__(self, to_match, rule_name='', root=False, ignore_case=None, multiline=None, str_repr=None, re_flags=re.MULTILINE, **kwargs): super(RegExMatch, self).__init__(rule_name, root, **kwargs) self.to_match_regex = to_match self.ignore_case = ignore_case self.multiline = multiline self.explicit_flags = re_flags self.to_match = str_repr if str_repr is not None else to_match
(self, to_match, rule_name='', root=False, ignore_case=None, multiline=None, str_repr=None, re_flags=re.MULTILINE, **kwargs)
157
arpeggio
_parse
null
def _parse(self, parser): c_pos = parser.position m = self.regex.match(parser.input, c_pos) if m: matched = m.group() if parser.debug: parser.dprint( "++ Match '%s' at %d => '%s'" % (matched, c_pos, parser.context(len(matched)))) parser.position += len(matched) if matched: return Terminal(self, c_pos, matched, extra_info=m) else: if parser.debug: parser.dprint("-- NoMatch at {}".format(c_pos)) parser._nm_raise(self, c_pos, parser)
(self, parser)
159
arpeggio
compile
null
def compile(self): flags = self.explicit_flags if self.multiline is True: flags |= re.DOTALL if self.multiline is False and flags & re.DOTALL: flags -= re.DOTALL if self.ignore_case is True: flags |= re.IGNORECASE if self.ignore_case is False and flags & re.IGNORECASE: flags -= re.IGNORECASE self.regex = re.compile(self.to_match_regex, flags)
(self)
161
arpeggio
Repetition
Base class for all repetition-like parser expressions (?,*,+) Args: eolterm(bool): Flag that indicates that end of line should terminate repetition match.
class Repetition(ParsingExpression): """ Base class for all repetition-like parser expressions (?,*,+) Args: eolterm(bool): Flag that indicates that end of line should terminate repetition match. """ def __init__(self, *elements, **kwargs): super(Repetition, self).__init__(*elements, **kwargs) self.eolterm = kwargs.get('eolterm', False) self.sep = kwargs.get('sep', None)
(*elements, **kwargs)
165
arpeggio
SemanticAction
Semantic actions are executed during semantic analysis. They are in charge of producing Abstract Semantic Graph (ASG) out of the parse tree. Every non-terminal and terminal can have semantic action defined which will be triggered during semantic analysis. Semantic action triggering is separated in two passes. first_pass method is required and the method called second_pass is optional and will be called if exists after the first pass. Second pass can be used for forward referencing, e.g. linking to the declaration registered in the first pass stage.
class SemanticAction(object): """ Semantic actions are executed during semantic analysis. They are in charge of producing Abstract Semantic Graph (ASG) out of the parse tree. Every non-terminal and terminal can have semantic action defined which will be triggered during semantic analysis. Semantic action triggering is separated in two passes. first_pass method is required and the method called second_pass is optional and will be called if exists after the first pass. Second pass can be used for forward referencing, e.g. linking to the declaration registered in the first pass stage. """ def first_pass(self, parser, node, nodes): """ Called in the first pass of tree walk. This is the default implementation used if no semantic action is defined. """ if isinstance(node, Terminal): # Default for Terminal is to convert to string unless suppress flag # is set in which case it is suppressed by setting to None. retval = text(node) if not node.suppress else None else: retval = node # Special case. If only one child exist return it. if len(nodes) == 1: retval = nodes[0] else: # If there is only one non-string child return # that by default. This will support e.g. bracket # removals. last_non_str = None for c in nodes: if not isstr(c): if last_non_str is None: last_non_str = c else: # If there is multiple non-string objects # by default convert non-terminal to string if parser.debug: parser.dprint( "*** Warning: Multiple non-" "string objects found in applying " "default semantic action. Converting " "non-terminal to string.") retval = text(node) break else: # Return the only non-string child retval = last_non_str return retval
()
166
arpeggio
first_pass
Called in the first pass of tree walk. This is the default implementation used if no semantic action is defined.
def first_pass(self, parser, node, nodes): """ Called in the first pass of tree walk. This is the default implementation used if no semantic action is defined. """ if isinstance(node, Terminal): # Default for Terminal is to convert to string unless suppress flag # is set in which case it is suppressed by setting to None. retval = text(node) if not node.suppress else None else: retval = node # Special case. If only one child exist return it. if len(nodes) == 1: retval = nodes[0] else: # If there is only one non-string child return # that by default. This will support e.g. bracket # removals. last_non_str = None for c in nodes: if not isstr(c): if last_non_str is None: last_non_str = c else: # If there is multiple non-string objects # by default convert non-terminal to string if parser.debug: parser.dprint( "*** Warning: Multiple non-" "string objects found in applying " "default semantic action. Converting " "non-terminal to string.") retval = text(node) break else: # Return the only non-string child retval = last_non_str return retval
(self, parser, node, nodes)
167
arpeggio
SemanticActionBodyWithBraces
null
class SemanticActionBodyWithBraces(SemanticAction): def first_pass(self, parser, node, children): return children[1:-1]
()
168
arpeggio
first_pass
null
def first_pass(self, parser, node, children): return children[1:-1]
(self, parser, node, children)
169
arpeggio
SemanticActionResults
Used in visitor methods call to supply results of semantic analysis of children parse tree nodes. Enables dot access by the name of the rule similar to NonTerminal tree navigation. Enables index access as well as iteration.
class SemanticActionResults(list): """ Used in visitor methods call to supply results of semantic analysis of children parse tree nodes. Enables dot access by the name of the rule similar to NonTerminal tree navigation. Enables index access as well as iteration. """ def __init__(self): self.results = {} def append_result(self, name, result): if name: if name not in self.results: self.results[name] = [] self.results[name].append(result) self.append(result) def __getattr__(self, attr_name): if attr_name == 'results': raise AttributeError return self.results.get(attr_name, [])
()
170
arpeggio
__getattr__
null
def __getattr__(self, attr_name): if attr_name == 'results': raise AttributeError return self.results.get(attr_name, [])
(self, attr_name)
171
arpeggio
__init__
null
def __init__(self): self.results = {}
(self)
172
arpeggio
append_result
null
def append_result(self, name, result): if name: if name not in self.results: self.results[name] = [] self.results[name].append(result) self.append(result)
(self, name, result)
173
arpeggio
SemanticActionSingleChild
null
class SemanticActionSingleChild(SemanticAction): def first_pass(self, parser, node, children): return children[0]
()
174
arpeggio
first_pass
null
def first_pass(self, parser, node, children): return children[0]
(self, parser, node, children)
175
arpeggio
SemanticActionToString
null
class SemanticActionToString(SemanticAction): def first_pass(self, parser, node, children): return text(node)
()
176
arpeggio
first_pass
null
def first_pass(self, parser, node, children): return text(node)
(self, parser, node, children)
177
arpeggio
SemanticError
Error raised during the phase of semantic analysis used to indicate semantic error.
class SemanticError(ArpeggioError): """ Error raised during the phase of semantic analysis used to indicate semantic error. """
(message)
180
arpeggio
Sequence
Will match sequence of parser expressions in exact order they are defined.
class Sequence(ParsingExpression): """ Will match sequence of parser expressions in exact order they are defined. """ def __init__(self, *elements, **kwargs): super(Sequence, self).__init__(*elements, **kwargs) self.ws = kwargs.pop('ws', None) self.skipws = kwargs.pop('skipws', None) def _parse(self, parser): results = [] c_pos = parser.position if self.ws is not None: old_ws = parser.ws parser.ws = self.ws if self.skipws is not None: old_skipws = parser.skipws parser.skipws = self.skipws # Prefetching append = results.append try: for e in self.nodes: result = e.parse(parser) if result: append(result) except NoMatch: parser.position = c_pos # Backtracking raise finally: if self.ws is not None: parser.ws = old_ws if self.skipws is not None: parser.skipws = old_skipws if results: return results
(*elements, **kwargs)
183
arpeggio
_parse
null
def _parse(self, parser): results = [] c_pos = parser.position if self.ws is not None: old_ws = parser.ws parser.ws = self.ws if self.skipws is not None: old_skipws = parser.skipws parser.skipws = self.skipws # Prefetching append = results.append try: for e in self.nodes: result = e.parse(parser) if result: append(result) except NoMatch: parser.position = c_pos # Backtracking raise finally: if self.ws is not None: parser.ws = old_ws if self.skipws is not None: parser.skipws = old_skipws if results: return results
(self, parser)
185
arpeggio
StrMatch
This Match class will perform input matching by a string comparison. Args: to_match (str): A string to match. ignore_case(bool): If case insensitive match is needed. Default is None to support propagation from global parser setting.
class StrMatch(Match): """ This Match class will perform input matching by a string comparison. Args: to_match (str): A string to match. ignore_case(bool): If case insensitive match is needed. Default is None to support propagation from global parser setting. """ def __init__(self, to_match, rule_name='', root=False, ignore_case=None, **kwargs): super(StrMatch, self).__init__(rule_name, root, **kwargs) self.to_match = to_match self.ignore_case = ignore_case def _parse(self, parser): c_pos = parser.position input_frag = parser.input[c_pos:c_pos+len(self.to_match)] if self.ignore_case: match = input_frag.lower() == self.to_match.lower() else: match = input_frag == self.to_match if match: if parser.debug: parser.dprint( "++ Match '{}' at {} => '{}'" .format(self.to_match, c_pos, parser.context(len(self.to_match)))) parser.position += len(self.to_match) # If this match is inside sequence than mark for suppression suppress = type(parser.last_pexpression) is Sequence return Terminal(self, c_pos, self.to_match, suppress=suppress) else: if parser.debug: parser.dprint( "-- No match '{}' at {} => '{}'" .format(self.to_match, c_pos, parser.context(len(self.to_match)))) parser._nm_raise(self, c_pos, parser) def __str__(self): return self.to_match def __unicode__(self): return self.__str__() def __eq__(self, other): return self.to_match == text(other) def __hash__(self): return hash(self.to_match)
(to_match, rule_name='', root=False, ignore_case=None, **kwargs)
188
arpeggio
__init__
null
def __init__(self, to_match, rule_name='', root=False, ignore_case=None, **kwargs): super(StrMatch, self).__init__(rule_name, root, **kwargs) self.to_match = to_match self.ignore_case = ignore_case
(self, to_match, rule_name='', root=False, ignore_case=None, **kwargs)
195
arpeggio
SyntaxPredicate
Base class for all syntax predicates (and, not, empty). Predicates are parser expressions that will do the match but will not consume any input.
class SyntaxPredicate(ParsingExpression): """ Base class for all syntax predicates (and, not, empty). Predicates are parser expressions that will do the match but will not consume any input. """
(*elements, **kwargs)
199
arpeggio
Terminal
Leaf node of the Parse Tree. Represents matched string. Attributes: rule (ParsingExpression): The rule that created this terminal. position (int): A position in the input stream where match occurred. value (str): Matched string at the given position or missing token name in the case of an error node. suppress(bool): If True this terminal can be ignored in semantic analysis. extra_info(object): additional information (e.g. the re matcher object)
class Terminal(ParseTreeNode): """ Leaf node of the Parse Tree. Represents matched string. Attributes: rule (ParsingExpression): The rule that created this terminal. position (int): A position in the input stream where match occurred. value (str): Matched string at the given position or missing token name in the case of an error node. suppress(bool): If True this terminal can be ignored in semantic analysis. extra_info(object): additional information (e.g. the re matcher object) """ __slots__ = ['rule', 'rule_name', 'position', 'error', 'comments', 'value', 'suppress', 'extra_info'] def __init__(self, rule, position, value, error=False, suppress=False, extra_info=None): super(Terminal, self).__init__(rule, position, error) self.value = value self.suppress = suppress self.extra_info = extra_info @property def desc(self): if self.value: return "%s '%s' [%s]" % (self.rule_name, self.value, self.position) else: return "%s [%s]" % (self.rule_name, self.position) @property def position_end(self): return self.position + len(self.value) def flat_str(self): return self.value def __str__(self): return self.value def __unicode__(self): return self.__str__() def __repr__(self): return self.desc def tree_str(self, indent=0): return '{}: {}'.format(super(Terminal, self).tree_str(indent), self.value) def __eq__(self, other): return text(self) == text(other)
(rule, position, value, error=False, suppress=False, extra_info=None)
200
arpeggio
__eq__
null
def __eq__(self, other): return text(self) == text(other)
(self, other)
201
arpeggio
__init__
null
def __init__(self, rule, position, value, error=False, suppress=False, extra_info=None): super(Terminal, self).__init__(rule, position, error) self.value = value self.suppress = suppress self.extra_info = extra_info
(self, rule, position, value, error=False, suppress=False, extra_info=None)
202
arpeggio
__repr__
null
def __repr__(self): return self.desc
(self)
203
arpeggio
__str__
null
def __str__(self): return self.value
(self)
205
arpeggio
flat_str
null
def flat_str(self): return self.value
(self)
206
arpeggio
tree_str
null
def tree_str(self, indent=0): return '{}: {}'.format(super(Terminal, self).tree_str(indent), self.value)
(self, indent=0)
208
arpeggio
UnorderedGroup
Will try to match all of the parsing expression in any order.
class UnorderedGroup(Repetition): """ Will try to match all of the parsing expression in any order. """ def _parse(self, parser): results = [] c_pos = parser.position if self.eolterm: # Remember current eolterm and set eolterm of # this repetition old_eolterm = parser.eolterm parser.eolterm = self.eolterm # Prefetching append = results.append nodes_to_try = list(self.nodes) sep = self.sep.parse if self.sep else None result = None sep_result = None first = True while nodes_to_try: sep_exc = None # Separator c_loc_pos_sep = parser.position if sep and not first: try: sep_result = sep(parser) except NoMatch as e: parser.position = c_loc_pos_sep # Backtracking # This still might be valid if all remaining subexpressions # are optional and none of them will match sep_exc = e c_loc_pos = parser.position match = True all_optionals_fail = True for e in list(nodes_to_try): try: result = e.parse(parser) if result: if sep_exc: raise sep_exc if sep_result: append(sep_result) first = False match = True all_optionals_fail = False append(result) nodes_to_try.remove(e) break except NoMatch: match = False parser.position = c_loc_pos # local backtracking if not match or all_optionals_fail: # If sep is matched backtrack it parser.position = c_loc_pos_sep break if self.eolterm: # Restore previous eolterm parser.eolterm = old_eolterm if not match: # Unsuccessful match of the whole PE - full backtracking parser.position = c_pos parser._nm_raise(self, c_pos, parser) if results: return results
(*elements, **kwargs)
211
arpeggio
_parse
null
def _parse(self, parser): results = [] c_pos = parser.position if self.eolterm: # Remember current eolterm and set eolterm of # this repetition old_eolterm = parser.eolterm parser.eolterm = self.eolterm # Prefetching append = results.append nodes_to_try = list(self.nodes) sep = self.sep.parse if self.sep else None result = None sep_result = None first = True while nodes_to_try: sep_exc = None # Separator c_loc_pos_sep = parser.position if sep and not first: try: sep_result = sep(parser) except NoMatch as e: parser.position = c_loc_pos_sep # Backtracking # This still might be valid if all remaining subexpressions # are optional and none of them will match sep_exc = e c_loc_pos = parser.position match = True all_optionals_fail = True for e in list(nodes_to_try): try: result = e.parse(parser) if result: if sep_exc: raise sep_exc if sep_result: append(sep_result) first = False match = True all_optionals_fail = False append(result) nodes_to_try.remove(e) break except NoMatch: match = False parser.position = c_loc_pos # local backtracking if not match or all_optionals_fail: # If sep is matched backtrack it parser.position = c_loc_pos_sep break if self.eolterm: # Restore previous eolterm parser.eolterm = old_eolterm if not match: # Unsuccessful match of the whole PE - full backtracking parser.position = c_pos parser._nm_raise(self, c_pos, parser) if results: return results
(self, parser)
213
arpeggio
ZeroOrMore
ZeroOrMore will try to match parser expression specified zero or more times. It will never fail.
class ZeroOrMore(Repetition): """ ZeroOrMore will try to match parser expression specified zero or more times. It will never fail. """ def _parse(self, parser): results = [] if self.eolterm: # Remember current eolterm and set eolterm of # this repetition old_eolterm = parser.eolterm parser.eolterm = self.eolterm # Prefetching append = results.append p = self.nodes[0].parse sep = self.sep.parse if self.sep else None result = None while True: try: c_pos = parser.position if sep and result: sep_result = sep(parser) if sep_result: append(sep_result) result = p(parser) if not result: break append(result) except NoMatch: parser.position = c_pos # Backtracking break if self.eolterm: # Restore previous eolterm parser.eolterm = old_eolterm return results
(*elements, **kwargs)
216
arpeggio
_parse
null
def _parse(self, parser): results = [] if self.eolterm: # Remember current eolterm and set eolterm of # this repetition old_eolterm = parser.eolterm parser.eolterm = self.eolterm # Prefetching append = results.append p = self.nodes[0].parse sep = self.sep.parse if self.sep else None result = None while True: try: c_pos = parser.position if sep and result: sep_result = sep(parser) if sep_result: append(sep_result) result = p(parser) if not result: break append(result) except NoMatch: parser.position = c_pos # Backtracking break if self.eolterm: # Restore previous eolterm parser.eolterm = old_eolterm return results
(self, parser)
220
arpeggio
flatten
Flattening of python iterables.
def flatten(_iterable): '''Flattening of python iterables.''' result = [] for e in _iterable: if hasattr(e, "__iter__") and not type(e) in [text, NonTerminal]: result.extend(flatten(e)) else: result.append(e) return result
(_iterable)
221
arpeggio.utils
isstr
null
def isstr(s): return isinstance(s, str)
(s)
227
arpeggio
visit_parse_tree
Applies visitor to parse_tree and runs the second pass afterwards. Args: parse_tree(ParseTreeNode): visitor(PTNodeVisitor):
def visit_parse_tree(parse_tree, visitor): """ Applies visitor to parse_tree and runs the second pass afterwards. Args: parse_tree(ParseTreeNode): visitor(PTNodeVisitor): """ if not parse_tree: raise Exception( "Parse tree is empty. You did call parse(), didn't you?") if visitor.debug: visitor.dprint("ASG: First pass") # Visit tree. result = parse_tree.visit(visitor) # Second pass if visitor.debug: visitor.dprint("ASG: Second pass") for sa_name, asg_node in visitor.for_second_pass: getattr(visitor, "second_%s" % sa_name)(asg_node) return result
(parse_tree, visitor)
228
datetime
datetime
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.
class datetime(date): """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. """ __slots__ = date.__slots__ + time.__slots__ def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0): if (isinstance(year, (bytes, str)) and len(year) == 10 and 1 <= ord(year[2:3])&0x7F <= 12): # Pickle support if isinstance(year, str): try: year = bytes(year, 'latin1') except UnicodeEncodeError: # More informative error message. raise ValueError( "Failed to encode latin1 string when unpickling " "a datetime object. " "pickle.load(data, encoding='latin1') is assumed.") self = object.__new__(cls) self.__setstate(year, month) self._hashcode = -1 return self year, month, day = _check_date_fields(year, month, day) hour, minute, second, microsecond, fold = _check_time_fields( hour, minute, second, microsecond, fold) _check_tzinfo_arg(tzinfo) self = object.__new__(cls) self._year = year self._month = month self._day = day self._hour = hour self._minute = minute self._second = second self._microsecond = microsecond self._tzinfo = tzinfo self._hashcode = -1 self._fold = fold return self # Read-only field accessors @property def hour(self): """hour (0-23)""" return self._hour @property def minute(self): """minute (0-59)""" return self._minute @property def second(self): """second (0-59)""" return self._second @property def microsecond(self): """microsecond (0-999999)""" return self._microsecond @property def tzinfo(self): """timezone info object""" return self._tzinfo @property def fold(self): return self._fold @classmethod def _fromtimestamp(cls, t, utc, tz): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ frac, t = _math.modf(t) us = round(frac * 1e6) if us >= 1000000: t += 1 us -= 1000000 elif us < 0: t -= 1 us += 1000000 converter = _time.gmtime if utc else _time.localtime y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) ss = min(ss, 59) # clamp out leap seconds if the platform has them result = cls(y, m, d, hh, mm, ss, us, tz) if tz is None and not utc: # As of version 2015f max fold in IANA database is # 23 hours at 1969-09-30 13:00:00 in Kwajalein. # Let's probe 24 hours in the past to detect a transition: max_fold_seconds = 24 * 3600 # On Windows localtime_s throws an OSError for negative values, # thus we can't perform fold detection for values of time less # than the max time fold. See comments in _datetimemodule's # version of this method for more details. if t < max_fold_seconds and sys.platform.startswith("win"): return result y, m, d, hh, mm, ss = converter(t - max_fold_seconds)[:6] probe1 = cls(y, m, d, hh, mm, ss, us, tz) trans = result - probe1 - timedelta(0, max_fold_seconds) if trans.days < 0: y, m, d, hh, mm, ss = converter(t + trans // timedelta(0, 1))[:6] probe2 = cls(y, m, d, hh, mm, ss, us, tz) if probe2 == result: result._fold = 1 elif tz is not None: result = tz.fromutc(result) return result @classmethod def fromtimestamp(cls, t, tz=None): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ _check_tzinfo_arg(tz) return cls._fromtimestamp(t, tz is not None, tz) @classmethod def utcfromtimestamp(cls, t): """Construct a naive UTC datetime from a POSIX timestamp.""" return cls._fromtimestamp(t, True, None) @classmethod def now(cls, tz=None): "Construct a datetime from time.time() and optional time zone info." t = _time.time() return cls.fromtimestamp(t, tz) @classmethod def utcnow(cls): "Construct a UTC datetime from time.time()." t = _time.time() return cls.utcfromtimestamp(t) @classmethod def combine(cls, date, time, tzinfo=True): "Construct a datetime from a given date and a given time." if not isinstance(date, _date_class): raise TypeError("date argument must be a date instance") if not isinstance(time, _time_class): raise TypeError("time argument must be a time instance") if tzinfo is True: tzinfo = time.tzinfo return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, tzinfo, fold=time.fold) @classmethod def fromisoformat(cls, date_string): """Construct a datetime from the output of datetime.isoformat().""" if not isinstance(date_string, str): raise TypeError('fromisoformat: argument must be str') # Split this at the separator dstr = date_string[0:10] tstr = date_string[11:] try: date_components = _parse_isoformat_date(dstr) except ValueError: raise ValueError(f'Invalid isoformat string: {date_string!r}') if tstr: try: time_components = _parse_isoformat_time(tstr) except ValueError: raise ValueError(f'Invalid isoformat string: {date_string!r}') else: time_components = [0, 0, 0, 0, None] return cls(*(date_components + time_components)) def timetuple(self): "Return local time tuple compatible with time.localtime()." dst = self.dst() if dst is None: dst = -1 elif dst: dst = 1 else: dst = 0 return _build_struct_time(self.year, self.month, self.day, self.hour, self.minute, self.second, dst) def _mktime(self): """Return integer POSIX timestamp.""" epoch = datetime(1970, 1, 1) max_fold_seconds = 24 * 3600 t = (self - epoch) // timedelta(0, 1) def local(u): y, m, d, hh, mm, ss = _time.localtime(u)[:6] return (datetime(y, m, d, hh, mm, ss) - epoch) // timedelta(0, 1) # Our goal is to solve t = local(u) for u. a = local(t) - t u1 = t - a t1 = local(u1) if t1 == t: # We found one solution, but it may not be the one we need. # Look for an earlier solution (if `fold` is 0), or a # later one (if `fold` is 1). u2 = u1 + (-max_fold_seconds, max_fold_seconds)[self.fold] b = local(u2) - u2 if a == b: return u1 else: b = t1 - u1 assert a != b u2 = t - b t2 = local(u2) if t2 == t: return u2 if t1 == t: return u1 # We have found both offsets a and b, but neither t - a nor t - b is # a solution. This means t is in the gap. return (max, min)[self.fold](u1, u2) def timestamp(self): "Return POSIX timestamp as float" if self._tzinfo is None: s = self._mktime() return s + self.microsecond / 1e6 else: return (self - _EPOCH).total_seconds() def utctimetuple(self): "Return UTC time tuple compatible with time.gmtime()." offset = self.utcoffset() if offset: self -= offset y, m, d = self.year, self.month, self.day hh, mm, ss = self.hour, self.minute, self.second return _build_struct_time(y, m, d, hh, mm, ss, 0) def date(self): "Return the date part." return date(self._year, self._month, self._day) def time(self): "Return the time part, with tzinfo None." return time(self.hour, self.minute, self.second, self.microsecond, fold=self.fold) def timetz(self): "Return the time part, with same tzinfo." return time(self.hour, self.minute, self.second, self.microsecond, self._tzinfo, fold=self.fold) def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=True, *, fold=None): """Return a new datetime with new values for the specified fields.""" if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if hour is None: hour = self.hour if minute is None: minute = self.minute if second is None: second = self.second if microsecond is None: microsecond = self.microsecond if tzinfo is True: tzinfo = self.tzinfo if fold is None: fold = self.fold return type(self)(year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold) def _local_timezone(self): if self.tzinfo is None: ts = self._mktime() else: ts = (self - _EPOCH) // timedelta(seconds=1) localtm = _time.localtime(ts) local = datetime(*localtm[:6]) # Extract TZ data gmtoff = localtm.tm_gmtoff zone = localtm.tm_zone return timezone(timedelta(seconds=gmtoff), zone) def astimezone(self, tz=None): if tz is None: tz = self._local_timezone() elif not isinstance(tz, tzinfo): raise TypeError("tz argument must be an instance of tzinfo") mytz = self.tzinfo if mytz is None: mytz = self._local_timezone() myoffset = mytz.utcoffset(self) else: myoffset = mytz.utcoffset(self) if myoffset is None: mytz = self.replace(tzinfo=None)._local_timezone() myoffset = mytz.utcoffset(self) if tz is mytz: return self # Convert self to UTC, and attach the new time zone object. utc = (self - myoffset).replace(tzinfo=tz) # Convert from UTC to tz's local time. return tz.fromutc(utc) # Ways to produce a string. def ctime(self): "Return ctime() style string." weekday = self.toordinal() % 7 or 7 return "%s %s %2d %02d:%02d:%02d %04d" % ( _DAYNAMES[weekday], _MONTHNAMES[self._month], self._day, self._hour, self._minute, self._second, self._year) def isoformat(self, sep='T', timespec='auto'): """Return the time formatted according to ISO. The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'. By default, the fractional part is omitted if self.microsecond == 0. If self.tzinfo is not None, the UTC offset is also attached, giving giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'. Optional argument sep specifies the separator between date and time, default 'T'. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds' and 'microseconds'. """ s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) + _format_time(self._hour, self._minute, self._second, self._microsecond, timespec)) off = self.utcoffset() tz = _format_offset(off) if tz: s += tz return s def __repr__(self): """Convert to formal string, for repr().""" L = [self._year, self._month, self._day, # These are never zero self._hour, self._minute, self._second, self._microsecond] if L[-1] == 0: del L[-1] if L[-1] == 0: del L[-1] s = "%s.%s(%s)" % (self.__class__.__module__, self.__class__.__qualname__, ", ".join(map(str, L))) if self._tzinfo is not None: assert s[-1:] == ")" s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" if self._fold: assert s[-1:] == ")" s = s[:-1] + ", fold=1)" return s def __str__(self): "Convert to string, for str()." return self.isoformat(sep=' ') @classmethod def strptime(cls, date_string, format): 'string, format -> new datetime parsed from a string (like time.strptime()).' import _strptime return _strptime._strptime_datetime(cls, date_string, format) def utcoffset(self): """Return the timezone offset as timedelta positive east of UTC (negative west of UTC).""" if self._tzinfo is None: return None offset = self._tzinfo.utcoffset(self) _check_utc_offset("utcoffset", offset) return offset def tzname(self): """Return the timezone name. Note that the name is 100% informational -- there's no requirement that it mean anything in particular. For example, "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies. """ if self._tzinfo is None: return None name = self._tzinfo.tzname(self) _check_tzname(name) return name def dst(self): """Return 0 if DST is not in effect, or the DST offset (as timedelta positive eastward) if DST is in effect. This is purely informational; the DST offset has already been added to the UTC offset returned by utcoffset() if applicable, so there's no need to consult dst() unless you're interested in displaying the DST info. """ if self._tzinfo is None: return None offset = self._tzinfo.dst(self) _check_utc_offset("dst", offset) return offset # Comparisons of datetime objects with other. def __eq__(self, other): if isinstance(other, datetime): return self._cmp(other, allow_mixed=True) == 0 elif not isinstance(other, date): return NotImplemented else: return False def __le__(self, other): if isinstance(other, datetime): return self._cmp(other) <= 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def __lt__(self, other): if isinstance(other, datetime): return self._cmp(other) < 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def __ge__(self, other): if isinstance(other, datetime): return self._cmp(other) >= 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def __gt__(self, other): if isinstance(other, datetime): return self._cmp(other) > 0 elif not isinstance(other, date): return NotImplemented else: _cmperror(self, other) def _cmp(self, other, allow_mixed=False): assert isinstance(other, datetime) mytz = self._tzinfo ottz = other._tzinfo myoff = otoff = None if mytz is ottz: base_compare = True else: myoff = self.utcoffset() otoff = other.utcoffset() # Assume that allow_mixed means that we are called from __eq__ if allow_mixed: if myoff != self.replace(fold=not self.fold).utcoffset(): return 2 if otoff != other.replace(fold=not other.fold).utcoffset(): return 2 base_compare = myoff == otoff if base_compare: return _cmp((self._year, self._month, self._day, self._hour, self._minute, self._second, self._microsecond), (other._year, other._month, other._day, other._hour, other._minute, other._second, other._microsecond)) if myoff is None or otoff is None: if allow_mixed: return 2 # arbitrary non-zero value else: raise TypeError("cannot compare naive and aware datetimes") # XXX What follows could be done more efficiently... diff = self - other # this will take offsets into account if diff.days < 0: return -1 return diff and 1 or 0 def __add__(self, other): "Add a datetime and a timedelta." if not isinstance(other, timedelta): return NotImplemented delta = timedelta(self.toordinal(), hours=self._hour, minutes=self._minute, seconds=self._second, microseconds=self._microsecond) delta += other hour, rem = divmod(delta.seconds, 3600) minute, second = divmod(rem, 60) if 0 < delta.days <= _MAXORDINAL: return type(self).combine(date.fromordinal(delta.days), time(hour, minute, second, delta.microseconds, tzinfo=self._tzinfo)) raise OverflowError("result out of range") __radd__ = __add__ def __sub__(self, other): "Subtract two datetimes, or a datetime and a timedelta." if not isinstance(other, datetime): if isinstance(other, timedelta): return self + -other return NotImplemented days1 = self.toordinal() days2 = other.toordinal() secs1 = self._second + self._minute * 60 + self._hour * 3600 secs2 = other._second + other._minute * 60 + other._hour * 3600 base = timedelta(days1 - days2, secs1 - secs2, self._microsecond - other._microsecond) if self._tzinfo is other._tzinfo: return base myoff = self.utcoffset() otoff = other.utcoffset() if myoff == otoff: return base if myoff is None or otoff is None: raise TypeError("cannot mix naive and timezone-aware time") return base + otoff - myoff def __hash__(self): if self._hashcode == -1: if self.fold: t = self.replace(fold=0) else: t = self tzoff = t.utcoffset() if tzoff is None: self._hashcode = hash(t._getstate()[0]) else: days = _ymd2ord(self.year, self.month, self.day) seconds = self.hour * 3600 + self.minute * 60 + self.second self._hashcode = hash(timedelta(days, seconds, self.microsecond) - tzoff) return self._hashcode # Pickle support. def _getstate(self, protocol=3): yhi, ylo = divmod(self._year, 256) us2, us3 = divmod(self._microsecond, 256) us1, us2 = divmod(us2, 256) m = self._month if self._fold and protocol > 3: m += 128 basestate = bytes([yhi, ylo, m, self._day, self._hour, self._minute, self._second, us1, us2, us3]) if self._tzinfo is None: return (basestate,) else: return (basestate, self._tzinfo) def __setstate(self, string, tzinfo): if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class): raise TypeError("bad tzinfo state arg") (yhi, ylo, m, self._day, self._hour, self._minute, self._second, us1, us2, us3) = string if m > 127: self._fold = 1 self._month = m - 128 else: self._fold = 0 self._month = m self._year = yhi * 256 + ylo self._microsecond = (((us1 << 8) | us2) << 8) | us3 self._tzinfo = tzinfo def __reduce_ex__(self, protocol): return (self.__class__, self._getstate(protocol)) def __reduce__(self): return self.__reduce_ex__(2)
null
229
maya.core
MayaDT
The Maya Datetime object.
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc2822() def __format__(self, *args, **kwargs): """Return's the datetime's format""" return format(self.datetime(), *args, **kwargs) @validate_class_type_arguments('==') def __eq__(self, maya_dt): return int(self._epoch) == int(maya_dt._epoch) @validate_class_type_arguments('!=') def __ne__(self, maya_dt): return int(self._epoch) != int(maya_dt._epoch) @validate_class_type_arguments('<') def __lt__(self, maya_dt): return int(self._epoch) < int(maya_dt._epoch) @validate_class_type_arguments('<=') def __le__(self, maya_dt): return int(self._epoch) <= int(maya_dt._epoch) @validate_class_type_arguments('>') def __gt__(self, maya_dt): return int(self._epoch) > int(maya_dt._epoch) @validate_class_type_arguments('>=') def __ge__(self, maya_dt): return int(self._epoch) >= int(maya_dt._epoch) def __hash__(self): return hash(int(self.epoch)) def __add__(self, duration): return self.add( seconds=_seconds_or_timedelta(duration).total_seconds() ) def __radd__(self, duration): return self + duration def __sub__(self, duration_or_date): if isinstance(duration_or_date, MayaDT): return self.subtract_date(dt=duration_or_date) else: return self.subtract( seconds=_seconds_or_timedelta(duration_or_date).total_seconds() ) def add(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).add(**kwargs) ) def subtract(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).subtract(**kwargs) ) def subtract_date(self, **kwargs): """Returns a timedelta object with the duration between the dates""" return timedelta(seconds=self.epoch - kwargs['dt'].epoch) def snap(self, instruction): """ Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions. """ return self.from_datetime(snaptime.snap(self.datetime(), instruction)) # Timezone Crap # ------------- @property def timezone(self): """Returns the UTC tzinfo name. It's always UTC. Always.""" return 'UTC' @property def _tz(self): """Returns the UTC tzinfo object.""" return pytz.timezone(self.timezone) @property def local_timezone(self): """Returns the name of the local timezone.""" if self._local_tz.zone in pytz.all_timezones: return self._local_tz.zone return self.timezone @property def _local_tz(self): """Returns the local timezone.""" return get_localzone() @staticmethod @validate_arguments_type_of_function(Datetime) def __dt_to_epoch(dt): """Converts a datetime into an epoch.""" # Assume UTC if no datetime is provided. if dt.tzinfo is None: dt = dt.replace(tzinfo=pytz.utc) epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone('UTC')) return (dt - epoch_start).total_seconds() # Importers # --------- @classmethod @validate_arguments_type_of_function(Datetime) def from_datetime(klass, dt): """Returns MayaDT instance from datetime.""" return klass(klass.__dt_to_epoch(dt)) @classmethod @validate_arguments_type_of_function(time.struct_time) def from_struct(klass, struct, timezone=pytz.UTC): """Returns MayaDT instance from a 9-tuple struct It's assumed to be from gmtime(). """ struct_time = time.mktime(struct) - utc_offset(struct) dt = Datetime.fromtimestamp(struct_time, timezone) return klass(klass.__dt_to_epoch(dt)) @classmethod def from_iso8601(klass, iso8601_string): """Returns MayaDT instance from iso8601 string.""" return parse(iso8601_string) @staticmethod def from_rfc2822(rfc2822_string): """Returns MayaDT instance from rfc2822 string.""" return parse(rfc2822_string) @staticmethod def from_rfc3339(rfc3339_string): """Returns MayaDT instance from rfc3339 string.""" return parse(rfc3339_string) # Exporters # --------- def datetime(self, to_timezone=None, naive=False): """Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo is simply dropped (default: False) """ if to_timezone: dt = self.datetime().astimezone(pytz.timezone(to_timezone)) else: dt = Datetime.utcfromtimestamp(self._epoch) dt.replace(tzinfo=self._tz) # Strip the timezone info if requested to do so. if naive: return dt.replace(tzinfo=None) else: if dt.tzinfo is None: dt = dt.replace(tzinfo=self._tz) return dt def local_datetime(self): """Returns a local timezone-aware datetime object It's the same as: mayaDt.datetime(to_timezone=mayaDt.local_timezone) """ return self.datetime(to_timezone=self.local_timezone, naive=False) def iso8601(self): """Returns an ISO 8601 representation of the MayaDT.""" # Get a timezone-naive datetime. dt = self.datetime(naive=True) return '{}Z'.format(dt.isoformat()) def rfc2822(self): """Returns an RFC 2822 representation of the MayaDT.""" return email.utils.formatdate(self.epoch, usegmt=True) def rfc3339(self): """Returns an RFC 3339 representation of the MayaDT.""" return self.datetime().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-5] + "Z" # Properties # ---------- @property def year(self): return self.datetime().year @property def month(self): return self.datetime().month @property def day(self): return self.datetime().day @property def date(self): return self.datetime().date() @property def week(self): return self.datetime().isocalendar()[1] @property def weekday(self): """Return the day of the week as an integer. Monday is 1 and Sunday is 7. """ return self.datetime().isoweekday() @property def hour(self): return self.datetime().hour @property def minute(self): return self.datetime().minute @property def second(self): return self.datetime().second @property def microsecond(self): return self.datetime().microsecond @property def epoch(self): return int(self._epoch) # Human Slang Extras # ------------------ def slang_date(self, locale="en"): """"Returns human slang representation of date. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English) """ dt = pendulum.instance(self.datetime()) try: return _translate(dt, locale) except KeyError: pass delta = humanize.time.abs_timedelta( timedelta(seconds=(self.epoch - now().epoch))) format_string = "DD MMM" if delta.days >= 365: format_string += " YYYY" return dt.format(format_string, locale=locale).title() def slang_time(self, locale="en"): """"Returns human slang representation of time. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English) """ dt = self.datetime() return pendulum.instance(dt).diff_for_humans(locale=locale)
(epoch)
230
maya.core
wrapper
null
def validate_arguments_type_of_function(param_type=None): """ Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class. """ def inner(function): def wrapper(self, *args, **kwargs): type_ = param_type or type(self) for arg in args + tuple(kwargs.values()): if not isinstance(arg, type_): raise TypeError( ( 'Invalid Type: {}.{}() accepts only the ' 'arguments of type "<{}>"' ).format( type(self).__name__, function.__name__, type_.__name__, ) ) return function(self, *args, **kwargs) return wrapper return inner
(self, *args, **kwargs)
231
maya.core
__add__
null
def __add__(self, duration): return self.add( seconds=_seconds_or_timedelta(duration).total_seconds() )
(self, duration)
232
maya.core
wrapper
null
def validate_class_type_arguments(operator): """ Decorator to validate all the arguments to function are of the type of calling class for passed operator """ def inner(function): def wrapper(self, *args, **kwargs): for arg in args + tuple(kwargs.values()): if not isinstance(arg, self.__class__): raise TypeError( 'unorderable types: {}() {} {}()'.format( type(self).__name__, operator, type(arg).__name__ ) ) return function(self, *args, **kwargs) return wrapper return inner
(self, *args, **kwargs)
233
maya.core
__format__
Return's the datetime's format
def __format__(self, *args, **kwargs): """Return's the datetime's format""" return format(self.datetime(), *args, **kwargs)
(self, *args, **kwargs)
236
maya.core
__hash__
null
def __hash__(self): return hash(int(self.epoch))
(self)
237
maya.core
__init__
null
def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch
(self, epoch)
241
maya.core
__radd__
null
def __radd__(self, duration): return self + duration
(self, duration)
242
maya.core
__repr__
null
def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch)
(self)
243
maya.core
__str__
null
def __str__(self): return self.rfc2822()
(self)
244
maya.core
__sub__
null
def __sub__(self, duration_or_date): if isinstance(duration_or_date, MayaDT): return self.subtract_date(dt=duration_or_date) else: return self.subtract( seconds=_seconds_or_timedelta(duration_or_date).total_seconds() )
(self, duration_or_date)
245
maya.core
add
Returns a new MayaDT object with the given offsets.
def add(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).add(**kwargs) )
(self, **kwargs)
246
maya.core
datetime
Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo is simply dropped (default: False)
def datetime(self, to_timezone=None, naive=False): """Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo is simply dropped (default: False) """ if to_timezone: dt = self.datetime().astimezone(pytz.timezone(to_timezone)) else: dt = Datetime.utcfromtimestamp(self._epoch) dt.replace(tzinfo=self._tz) # Strip the timezone info if requested to do so. if naive: return dt.replace(tzinfo=None) else: if dt.tzinfo is None: dt = dt.replace(tzinfo=self._tz) return dt
(self, to_timezone=None, naive=False)
247
maya.core
from_rfc2822
Returns MayaDT instance from rfc2822 string.
@staticmethod def from_rfc2822(rfc2822_string): """Returns MayaDT instance from rfc2822 string.""" return parse(rfc2822_string)
(rfc2822_string)
248
maya.core
from_rfc3339
Returns MayaDT instance from rfc3339 string.
@staticmethod def from_rfc3339(rfc3339_string): """Returns MayaDT instance from rfc3339 string.""" return parse(rfc3339_string)
(rfc3339_string)
249
maya.core
iso8601
Returns an ISO 8601 representation of the MayaDT.
def iso8601(self): """Returns an ISO 8601 representation of the MayaDT.""" # Get a timezone-naive datetime. dt = self.datetime(naive=True) return '{}Z'.format(dt.isoformat())
(self)
250
maya.core
local_datetime
Returns a local timezone-aware datetime object It's the same as: mayaDt.datetime(to_timezone=mayaDt.local_timezone)
def local_datetime(self): """Returns a local timezone-aware datetime object It's the same as: mayaDt.datetime(to_timezone=mayaDt.local_timezone) """ return self.datetime(to_timezone=self.local_timezone, naive=False)
(self)
251
maya.core
rfc2822
Returns an RFC 2822 representation of the MayaDT.
def rfc2822(self): """Returns an RFC 2822 representation of the MayaDT.""" return email.utils.formatdate(self.epoch, usegmt=True)
(self)
252
maya.core
rfc3339
Returns an RFC 3339 representation of the MayaDT.
def rfc3339(self): """Returns an RFC 3339 representation of the MayaDT.""" return self.datetime().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-5] + "Z"
(self)
253
maya.core
slang_date
"Returns human slang representation of date. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English)
def slang_date(self, locale="en"): """"Returns human slang representation of date. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English) """ dt = pendulum.instance(self.datetime()) try: return _translate(dt, locale) except KeyError: pass delta = humanize.time.abs_timedelta( timedelta(seconds=(self.epoch - now().epoch))) format_string = "DD MMM" if delta.days >= 365: format_string += " YYYY" return dt.format(format_string, locale=locale).title()
(self, locale='en')
254
maya.core
slang_time
"Returns human slang representation of time. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English)
def slang_time(self, locale="en"): """"Returns human slang representation of time. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English) """ dt = self.datetime() return pendulum.instance(dt).diff_for_humans(locale=locale)
(self, locale='en')
255
maya.core
snap
Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions.
def snap(self, instruction): """ Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions. """ return self.from_datetime(snaptime.snap(self.datetime(), instruction))
(self, instruction)
256
maya.core
subtract
Returns a new MayaDT object with the given offsets.
def subtract(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).subtract(**kwargs) )
(self, **kwargs)
257
maya.core
subtract_date
Returns a timedelta object with the duration between the dates
def subtract_date(self, **kwargs): """Returns a timedelta object with the duration between the dates""" return timedelta(seconds=self.epoch - kwargs['dt'].epoch)
(self, **kwargs)
258
maya.core
MayaInterval
A MayaInterval represents a range between two datetimes, inclusive of the start and exclusive of the end.
class MayaInterval(object): """ A MayaInterval represents a range between two datetimes, inclusive of the start and exclusive of the end. """ def __init__(self, start=None, end=None, duration=None): try: # Ensure that proper arguments were passed. assert any( ( (start and end), (start and duration is not None), (end and duration is not None), ) ) assert not all((start, end, duration is not None)) except AssertionError: raise ValueError( 'Exactly 2 of start, end, and duration must be specified' ) # Convert duration to timedelta if seconds were provided. if duration: duration = _seconds_or_timedelta(duration) if not start: start = end - duration if not end: end = start + duration if start > end: raise ValueError('MayaInterval cannot end before it starts') self.start = start self.end = end def __repr__(self): return '<MayaInterval start={0!r} end={1!r}>'.format( self.start, self.end ) def iso8601(self): """Returns an ISO 8601 representation of the MayaInterval.""" return '{0}/{1}'.format(self.start.iso8601(), self.end.iso8601()) @classmethod def parse_iso8601_duration(cls, duration, start=None, end=None): match = re.match( r'(?:P(?P<weeks>\d+)W)|(?:P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D))?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?)', duration ) time_components = {} if match: time_components = match.groupdict(0) for key, value in time_components.items(): time_components[key] = int(value) duration = relativedelta(**time_components) if start: return parse(start.datetime() + duration) if end: return parse(end.datetime() - duration) return None @classmethod def from_iso8601(cls, s): # # Start and end, such as "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z" start, end = s.split('/') try: start = parse(start) except pendulum.parsing.exceptions.ParserError: # start = self._parse_iso8601_duration(start, end=end) raise NotImplementedError() try: end = parse(end) except (pendulum.parsing.exceptions.ParserError, TypeError) as e: end = cls.parse_iso8601_duration(end, start=start) return cls(start=start, end=end) # # Start and duration, such as "2007-03-01T13:00:00Z/P1Y2M10DT2H30M" # # Duration and end, such as "P1Y2M10DT2H30M/2008-05-11T15:30:00Z" @validate_arguments_type_of_function() def __and__(self, maya_interval): return self.intersection(maya_interval) @validate_arguments_type_of_function() def __or__(self, maya_interval): return self.combine(maya_interval) @validate_arguments_type_of_function() def __eq__(self, maya_interval): return ( self.start == maya_interval.start and self.end == maya_interval.end ) def __hash__(self): return hash((self.start, self.end)) def __iter__(self): yield self.start yield self.end @validate_arguments_type_of_function() def __cmp__(self, maya_interval): return ( cmp(self.start, maya_interval.start) or cmp(self.end, maya_interval.end) ) @property def duration(self): return self.timedelta.total_seconds() @property def timedelta(self): return timedelta(seconds=(self.end.epoch - self.start.epoch)) @property def is_instant(self): return self.timedelta == timedelta(seconds=0) def intersects(self, maya_interval): return self & maya_interval is not None @property def midpoint(self): return self.start.add(seconds=(self.duration / 2)) @validate_arguments_type_of_function() def combine(self, maya_interval): """Returns a combined list of timespans, merged together.""" interval_list = sorted([self, maya_interval]) if self & maya_interval or self.is_adjacent(maya_interval): return [ MayaInterval( interval_list[0].start, max(interval_list[0].end, interval_list[1].end), ) ] return interval_list @validate_arguments_type_of_function() def subtract(self, maya_interval): """"Removes the given interval.""" if not self & maya_interval: return [self] elif maya_interval.contains(self): return [] interval_list = [] if self.start < maya_interval.start: interval_list.append(MayaInterval(self.start, maya_interval.start)) if self.end > maya_interval.end: interval_list.append(MayaInterval(maya_interval.end, self.end)) return interval_list def split(self, duration, include_remainder=True): # Convert seconds to timedelta, if appropriate. duration = _seconds_or_timedelta(duration) if duration <= timedelta(seconds=0): raise ValueError('cannot call split with a non-positive timedelta') start = self.start while start < self.end: if start + duration <= self.end: yield MayaInterval(start, start + duration) elif include_remainder: yield MayaInterval(start, self.end) start += duration def quantize(self, duration, snap_out=False, timezone='UTC'): """Returns a quanitzed interval.""" # Convert seconds to timedelta, if appropriate. duration = _seconds_or_timedelta(duration) timezone = pytz.timezone(timezone) if duration <= timedelta(seconds=0): raise ValueError('cannot quantize by non-positive timedelta') epoch = timezone.localize(Datetime(1970, 1, 1)) seconds = int(duration.total_seconds()) start_seconds = int( (self.start.datetime(naive=False) - epoch).total_seconds() ) end_seconds = int( (self.end.datetime(naive=False) - epoch).total_seconds() ) if start_seconds % seconds and not snap_out: start_seconds += seconds if end_seconds % seconds and snap_out: end_seconds += seconds start_seconds -= start_seconds % seconds end_seconds -= end_seconds % seconds if start_seconds > end_seconds: start_seconds = end_seconds return MayaInterval( start=MayaDT.from_datetime(epoch).add(seconds=start_seconds), end=MayaDT.from_datetime(epoch).add(seconds=end_seconds), ) @validate_arguments_type_of_function() def intersection(self, maya_interval): """Returns the intersection between two intervals.""" start = max(self.start, maya_interval.start) end = min(self.end, maya_interval.end) either_instant = self.is_instant or maya_interval.is_instant instant_overlap = (self.start == maya_interval.start or start <= end) if (either_instant and instant_overlap) or (start < end): return MayaInterval(start, end) @validate_arguments_type_of_function() def contains(self, maya_interval): return ( self.start <= maya_interval.start and self.end >= maya_interval.end ) def __contains__(self, maya_dt): if isinstance(maya_dt, MayaDT): return self.contains_dt(maya_dt) return self.contains(maya_dt) def contains_dt(self, dt): return self.start <= dt < self.end @validate_arguments_type_of_function() def is_adjacent(self, maya_interval): return ( self.start == maya_interval.end or self.end == maya_interval.start ) @property def icalendar(self): ical_dt_format = '%Y%m%dT%H%M%SZ' return """ BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART:{0} DTEND:{1} END:VEVENT END:VCALENDAR """.format( self.start.datetime().strftime(ical_dt_format), self.end.datetime().strftime(ical_dt_format), ).replace( ' ', '' ).strip( '\r\n' ).replace( '\n', '\r\n' ) @staticmethod def flatten(interval_list): return functools.reduce( lambda reduced, maya_interval: ( ( reduced[:-1] + maya_interval.combine(reduced[-1]) ) if reduced else [ maya_interval ] ), sorted(interval_list), [], ) @classmethod def from_datetime(cls, start_dt=None, end_dt=None, duration=None): start = MayaDT.from_datetime(start_dt) if start_dt else None end = MayaDT.from_datetime(end_dt) if end_dt else None return cls(start=start, end=end, duration=duration)
(start=None, end=None, duration=None)
261
maya.core
__contains__
null
def __contains__(self, maya_dt): if isinstance(maya_dt, MayaDT): return self.contains_dt(maya_dt) return self.contains(maya_dt)
(self, maya_dt)
262
maya.compat
__eq__
null
def comparable(klass): """ Class decorator that ensures support for the special C{__cmp__} method. On Python 2 this does nothing. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class, relying on C{__cmp__} to implement their comparisons. """ # On Python 2, __cmp__ will just work, so no need to add extra methods: if not is_py3: return klass def __eq__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c == 0 def __ne__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c != 0 def __lt__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c < 0 def __le__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c <= 0 def __gt__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c > 0 def __ge__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c >= 0 klass.__lt__ = __lt__ klass.__gt__ = __gt__ klass.__le__ = __le__ klass.__ge__ = __ge__ klass.__eq__ = __eq__ klass.__ne__ = __ne__ return klass
(self, other)
265
maya.core
__hash__
null
def __hash__(self): return hash((self.start, self.end))
(self)
266
maya.core
__init__
null
def __init__(self, start=None, end=None, duration=None): try: # Ensure that proper arguments were passed. assert any( ( (start and end), (start and duration is not None), (end and duration is not None), ) ) assert not all((start, end, duration is not None)) except AssertionError: raise ValueError( 'Exactly 2 of start, end, and duration must be specified' ) # Convert duration to timedelta if seconds were provided. if duration: duration = _seconds_or_timedelta(duration) if not start: start = end - duration if not end: end = start + duration if start > end: raise ValueError('MayaInterval cannot end before it starts') self.start = start self.end = end
(self, start=None, end=None, duration=None)
267
maya.core
__iter__
null
def __iter__(self): yield self.start yield self.end
(self)
272
maya.core
__repr__
null
def __repr__(self): return '<MayaInterval start={0!r} end={1!r}>'.format( self.start, self.end )
(self)
275
maya.core
contains_dt
null
def contains_dt(self, dt): return self.start <= dt < self.end
(self, dt)
276
maya.core
flatten
null
@staticmethod def flatten(interval_list): return functools.reduce( lambda reduced, maya_interval: ( ( reduced[:-1] + maya_interval.combine(reduced[-1]) ) if reduced else [ maya_interval ] ), sorted(interval_list), [], )
(interval_list)
278
maya.core
intersects
null
def intersects(self, maya_interval): return self & maya_interval is not None
(self, maya_interval)
280
maya.core
iso8601
Returns an ISO 8601 representation of the MayaInterval.
def iso8601(self): """Returns an ISO 8601 representation of the MayaInterval.""" return '{0}/{1}'.format(self.start.iso8601(), self.end.iso8601())
(self)
281
maya.core
quantize
Returns a quanitzed interval.
def quantize(self, duration, snap_out=False, timezone='UTC'): """Returns a quanitzed interval.""" # Convert seconds to timedelta, if appropriate. duration = _seconds_or_timedelta(duration) timezone = pytz.timezone(timezone) if duration <= timedelta(seconds=0): raise ValueError('cannot quantize by non-positive timedelta') epoch = timezone.localize(Datetime(1970, 1, 1)) seconds = int(duration.total_seconds()) start_seconds = int( (self.start.datetime(naive=False) - epoch).total_seconds() ) end_seconds = int( (self.end.datetime(naive=False) - epoch).total_seconds() ) if start_seconds % seconds and not snap_out: start_seconds += seconds if end_seconds % seconds and snap_out: end_seconds += seconds start_seconds -= start_seconds % seconds end_seconds -= end_seconds % seconds if start_seconds > end_seconds: start_seconds = end_seconds return MayaInterval( start=MayaDT.from_datetime(epoch).add(seconds=start_seconds), end=MayaDT.from_datetime(epoch).add(seconds=end_seconds), )
(self, duration, snap_out=False, timezone='UTC')
282
maya.core
split
null
def split(self, duration, include_remainder=True): # Convert seconds to timedelta, if appropriate. duration = _seconds_or_timedelta(duration) if duration <= timedelta(seconds=0): raise ValueError('cannot call split with a non-positive timedelta') start = self.start while start < self.end: if start + duration <= self.end: yield MayaInterval(start, start + duration) elif include_remainder: yield MayaInterval(start, self.end) start += duration
(self, duration, include_remainder=True)
284
maya.compat
cmp
Compare two objects. Returns a negative number if C{a < b}, zero if they are equal, and a positive number if C{a > b}.
def cmp(a, b): """ Compare two objects. Returns a negative number if C{a < b}, zero if they are equal, and a positive number if C{a > b}. """ if a < b: return -1 elif a == b: return 0 else: return 1
(a, b)
285
maya.compat
comparable
Class decorator that ensures support for the special C{__cmp__} method. On Python 2 this does nothing. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class, relying on C{__cmp__} to implement their comparisons.
def comparable(klass): """ Class decorator that ensures support for the special C{__cmp__} method. On Python 2 this does nothing. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class, relying on C{__cmp__} to implement their comparisons. """ # On Python 2, __cmp__ will just work, so no need to add extra methods: if not is_py3: return klass def __eq__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c == 0 def __ne__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c != 0 def __lt__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c < 0 def __le__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c <= 0 def __gt__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c > 0 def __ge__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c >= 0 klass.__lt__ = __lt__ klass.__gt__ = __gt__ klass.__le__ = __le__ klass.__ge__ = __ge__ klass.__eq__ = __eq__ klass.__ne__ = __ne__ return klass
(klass)
290
maya.core
end_of_day_midnight
null
def end_of_day_midnight(dt): if dt.time() == time.min: return dt else: return ( dt.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1) )
(dt)
292
tzlocal.unix
get_localzone
Get the computers configured local timezone, if any.
def get_localzone() -> zoneinfo.ZoneInfo: """Get the computers configured local timezone, if any.""" global _cache_tz if _cache_tz is None: _cache_tz = _get_localzone() return _cache_tz
() -> zoneinfo.ZoneInfo
294
maya.core
intervals
Yields MayaDT objects between the start and end MayaDTs given, at a given interval (seconds or timedelta).
def intervals(start, end, interval): """ Yields MayaDT objects between the start and end MayaDTs given, at a given interval (seconds or timedelta). """ interval = _seconds_or_timedelta(interval) current_timestamp = start while current_timestamp.epoch < end.epoch: yield current_timestamp current_timestamp = current_timestamp.add( seconds=interval.total_seconds() )
(start, end, interval)
295
maya.core
now
Returns a MayaDT instance for this exact moment.
def now(): """Returns a MayaDT instance for this exact moment.""" epoch = time.time() return MayaDT(epoch=epoch)
()
296
maya.core
parse
"Returns a MayaDT instance for the machine-produced moment specified. Powered by pendulum. Accepts most known formats. Useful for working with data. Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') day_first -- if true, the first value (e.g. 01/05/2016) is parsed as day. if year_first is set to True, this distinguishes between YDM and YMD. (default: False) year_first -- if true, the first value (e.g. 2016/05/01) is parsed as year (default: True) strict -- if False, allow pendulum to fall back on datetime parsing if pendulum's own parsing fails
def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False): """"Returns a MayaDT instance for the machine-produced moment specified. Powered by pendulum. Accepts most known formats. Useful for working with data. Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') day_first -- if true, the first value (e.g. 01/05/2016) is parsed as day. if year_first is set to True, this distinguishes between YDM and YMD. (default: False) year_first -- if true, the first value (e.g. 2016/05/01) is parsed as year (default: True) strict -- if False, allow pendulum to fall back on datetime parsing if pendulum's own parsing fails """ options = {} options['tz'] = timezone options['day_first'] = day_first options['year_first'] = year_first options['strict'] = strict dt = pendulum.parse(str(string), **options) return MayaDT.from_datetime(dt)
(string, timezone='UTC', day_first=False, year_first=True, strict=False)
300
dateutil.relativedelta
relativedelta
The relativedelta type is designed to be applied to an existing datetime and can replace specific components of that datetime, or represents an interval of time. It is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime <https://www.egenix.com/products/python/mxBase/mxDateTime/>`_ extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:: relativedelta(datetime1, datetime2) The second one is passing it any number of the following keyword arguments:: relativedelta(arg1=x,arg2=y,arg3=z...) year, month, day, hour, minute, second, microsecond: Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an arithmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative (argument is plural); adding or subtracting a relativedelta with relative information performs the corresponding arithmetic operation on the original datetime value with the information in the relativedelta. weekday: One of the weekday instances (MO, TU, etc) available in the relativedelta module. These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2)). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. This argument is always relative e.g. if the calculated date is already Monday, using MO(1) or MO(-1) won't change the day. To effectively make it absolute, use it in combination with the day argument (e.g. day=1, MO(1) for first Monday of the month). leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. There are relative and absolute forms of the keyword arguments. The plural is relative, and the singular is absolute. For each argument in the order below, the absolute form is applied first (by setting each attribute to that value) and then the relative form (by adding the value to the attribute). The order of attributes considered when this relativedelta is added to a datetime is: 1. Year 2. Month 3. Day 4. Hours 5. Minutes 6. Seconds 7. Microseconds Finally, weekday is applied, using the rule described above. For example >>> from datetime import datetime >>> from dateutil.relativedelta import relativedelta, MO >>> dt = datetime(2018, 4, 9, 13, 37, 0) >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) >>> dt + delta datetime.datetime(2018, 4, 2, 14, 37) First, the day is set to 1 (the first of the month), then 25 hours are added, to get to the 2nd day and 14th hour, finally the weekday is applied, but since the 2nd is already a Monday there is no effect.
class relativedelta(object): """ The relativedelta type is designed to be applied to an existing datetime and can replace specific components of that datetime, or represents an interval of time. It is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime <https://www.egenix.com/products/python/mxBase/mxDateTime/>`_ extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:: relativedelta(datetime1, datetime2) The second one is passing it any number of the following keyword arguments:: relativedelta(arg1=x,arg2=y,arg3=z...) year, month, day, hour, minute, second, microsecond: Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an arithmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative (argument is plural); adding or subtracting a relativedelta with relative information performs the corresponding arithmetic operation on the original datetime value with the information in the relativedelta. weekday: One of the weekday instances (MO, TU, etc) available in the relativedelta module. These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2)). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. This argument is always relative e.g. if the calculated date is already Monday, using MO(1) or MO(-1) won't change the day. To effectively make it absolute, use it in combination with the day argument (e.g. day=1, MO(1) for first Monday of the month). leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. There are relative and absolute forms of the keyword arguments. The plural is relative, and the singular is absolute. For each argument in the order below, the absolute form is applied first (by setting each attribute to that value) and then the relative form (by adding the value to the attribute). The order of attributes considered when this relativedelta is added to a datetime is: 1. Year 2. Month 3. Day 4. Hours 5. Minutes 6. Seconds 7. Microseconds Finally, weekday is applied, using the rule described above. For example >>> from datetime import datetime >>> from dateutil.relativedelta import relativedelta, MO >>> dt = datetime(2018, 4, 9, 13, 37, 0) >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) >>> dt + delta datetime.datetime(2018, 4, 2, 14, 37) First, the day is set to 1 (the first of the month), then 25 hours are added, to get to the 2nd day and 14th hour, finally the weekday is applied, but since the 2nd is already a Monday there is no effect. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: # datetime is a subclass of date. So both must be date if not (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") # We allow two dates, or two datetimes, so we coerce them to be # of the same type if (isinstance(dt1, datetime.datetime) != isinstance(dt2, datetime.datetime)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 # Get year / month delta between the two months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) self._set_months(months) # Remove the year/month delta so the timedelta is just well-defined # time units (seconds, days and microseconds) dtm = self.__radd__(dt2) # If we've overshot our target, make an adjustment if dt1 < dt2: compare = operator.gt increment = 1 else: compare = operator.lt increment = -1 while compare(dt1, dtm): months += increment self._set_months(months) dtm = self.__radd__(dt2) # Get the timedelta between the "months-adjusted" date and dt1 delta = dt1 - dtm self.seconds = delta.seconds + delta.days * 86400 self.microseconds = delta.microseconds else: # Check for non-integer values in integer-only quantities if any(x is not None and x != int(x) for x in (years, months)): raise ValueError("Non-integer years and months are " "ambiguous and not currently supported.") # Relative information self.years = int(years) self.months = int(months) self.days = days + weeks * 7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds # Absolute information self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if any(x is not None and int(x) != x for x in (year, month, day, hour, minute, second, microsecond)): # For now we'll deprecate floats - later it'll be an error. warn("Non-integer value passed as absolute information. " + "This is not a well-defined condition and will raise " + "errors in future versions.", DeprecationWarning) if isinstance(weekday, integer_types): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = _sign(self.microseconds) div, mod = divmod(self.microseconds * s, 1000000) self.microseconds = mod * s self.seconds += div * s if abs(self.seconds) > 59: s = _sign(self.seconds) div, mod = divmod(self.seconds * s, 60) self.seconds = mod * s self.minutes += div * s if abs(self.minutes) > 59: s = _sign(self.minutes) div, mod = divmod(self.minutes * s, 60) self.minutes = mod * s self.hours += div * s if abs(self.hours) > 23: s = _sign(self.hours) div, mod = divmod(self.hours * s, 24) self.hours = mod * s self.days += div * s if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years += div * s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 @property def weeks(self): return int(self.days / 7.0) @weeks.setter def weeks(self, value): self.days = self.days - (self.weeks * 7) + value * 7 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years = div * s else: self.years = 0 def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=+1, hours=+14) :return: Returns a :class:`dateutil.relativedelta.relativedelta` object. """ # Cascade remainders down (rounding each to roughly nearest microsecond) days = int(self.days) hours_f = round(self.hours + 24 * (self.days - days), 11) hours = int(hours_f) minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) minutes = int(minutes_f) seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) seconds = int(seconds_f) microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) # Constructor carries overflow back up with call to _fix() return self.__class__(years=self.years, months=self.months, days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __add__(self, other): if isinstance(other, relativedelta): return self.__class__(years=other.years + self.years, months=other.months + self.months, days=other.days + self.days, hours=other.hours + self.hours, minutes=other.minutes + self.minutes, seconds=other.seconds + self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=(other.year if other.year is not None else self.year), month=(other.month if other.month is not None else self.month), day=(other.day if other.day is not None else self.day), weekday=(other.weekday if other.weekday is not None else self.weekday), hour=(other.hour if other.hour is not None else self.hour), minute=(other.minute if other.minute is not None else self.minute), second=(other.second if other.second is not None else self.second), microsecond=(other.microsecond if other.microsecond is not None else self.microsecond)) if isinstance(other, datetime.timedelta): return self.__class__(years=self.years, months=self.months, days=self.days + other.days, hours=self.hours, minutes=self.minutes, seconds=self.seconds + other.seconds, microseconds=self.microseconds + other.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) if not isinstance(other, datetime.date): return NotImplemented elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__neg__().__radd__(other) def __sub__(self, other): if not isinstance(other, relativedelta): return NotImplemented # In case the other object defines __rsub__ return self.__class__(years=self.years - other.years, months=self.months - other.months, days=self.days - other.days, hours=self.hours - other.hours, minutes=self.minutes - other.minutes, seconds=self.seconds - other.seconds, microseconds=self.microseconds - other.microseconds, leapdays=self.leapdays or other.leapdays, year=(self.year if self.year is not None else other.year), month=(self.month if self.month is not None else other.month), day=(self.day if self.day is not None else other.day), weekday=(self.weekday if self.weekday is not None else other.weekday), hour=(self.hour if self.hour is not None else other.hour), minute=(self.minute if self.minute is not None else other.minute), second=(self.second if self.second is not None else other.second), microsecond=(self.microsecond if self.microsecond is not None else other.microsecond)) def __abs__(self): return self.__class__(years=abs(self.years), months=abs(self.months), days=abs(self.days), hours=abs(self.hours), minutes=abs(self.minutes), seconds=abs(self.seconds), microseconds=abs(self.microseconds), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __neg__(self): return self.__class__(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) # Compatibility with Python 2.x __nonzero__ = __bool__ def __mul__(self, other): try: f = float(other) except TypeError: return NotImplemented return self.__class__(years=int(self.years * f), months=int(self.months * f), days=int(self.days * f), hours=int(self.hours * f), minutes=int(self.minutes * f), seconds=int(self.seconds * f), microseconds=int(self.microseconds * f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) __rmul__ = __mul__ def __eq__(self, other): if not isinstance(other, relativedelta): return NotImplemented if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.microseconds == other.microseconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __hash__(self): return hash(( self.weekday, self.years, self.months, self.days, self.hours, self.minutes, self.seconds, self.microseconds, self.leapdays, self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, )) def __ne__(self, other): return not self.__eq__(other) def __div__(self, other): try: reciprocal = 1 / float(other) except TypeError: return NotImplemented return self.__mul__(reciprocal) __truediv__ = __div__ def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("{attr}={value:+g}".format(attr=attr, value=value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("{attr}={value}".format(attr=attr, value=repr(value))) return "{classname}({attrs})".format(classname=self.__class__.__name__, attrs=", ".join(l))
(dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None)
301
dateutil.relativedelta
__abs__
null
def __abs__(self): return self.__class__(years=abs(self.years), months=abs(self.months), days=abs(self.days), hours=abs(self.hours), minutes=abs(self.minutes), seconds=abs(self.seconds), microseconds=abs(self.microseconds), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond)
(self)
302
dateutil.relativedelta
__add__
null
def __add__(self, other): if isinstance(other, relativedelta): return self.__class__(years=other.years + self.years, months=other.months + self.months, days=other.days + self.days, hours=other.hours + self.hours, minutes=other.minutes + self.minutes, seconds=other.seconds + self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=(other.year if other.year is not None else self.year), month=(other.month if other.month is not None else self.month), day=(other.day if other.day is not None else self.day), weekday=(other.weekday if other.weekday is not None else self.weekday), hour=(other.hour if other.hour is not None else self.hour), minute=(other.minute if other.minute is not None else self.minute), second=(other.second if other.second is not None else self.second), microsecond=(other.microsecond if other.microsecond is not None else self.microsecond)) if isinstance(other, datetime.timedelta): return self.__class__(years=self.years, months=self.months, days=self.days + other.days, hours=self.hours, minutes=self.minutes, seconds=self.seconds + other.seconds, microseconds=self.microseconds + other.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) if not isinstance(other, datetime.date): return NotImplemented elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret
(self, other)
303
dateutil.relativedelta
__bool__
null
def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None)
(self)
304
dateutil.relativedelta
__div__
null
def __div__(self, other): try: reciprocal = 1 / float(other) except TypeError: return NotImplemented return self.__mul__(reciprocal)
(self, other)
305
dateutil.relativedelta
__eq__
null
def __eq__(self, other): if not isinstance(other, relativedelta): return NotImplemented if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.microseconds == other.microseconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond)
(self, other)
306
dateutil.relativedelta
__hash__
null
def __hash__(self): return hash(( self.weekday, self.years, self.months, self.days, self.hours, self.minutes, self.seconds, self.microseconds, self.leapdays, self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, ))
(self)
307
dateutil.relativedelta
__init__
null
def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: # datetime is a subclass of date. So both must be date if not (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") # We allow two dates, or two datetimes, so we coerce them to be # of the same type if (isinstance(dt1, datetime.datetime) != isinstance(dt2, datetime.datetime)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 # Get year / month delta between the two months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) self._set_months(months) # Remove the year/month delta so the timedelta is just well-defined # time units (seconds, days and microseconds) dtm = self.__radd__(dt2) # If we've overshot our target, make an adjustment if dt1 < dt2: compare = operator.gt increment = 1 else: compare = operator.lt increment = -1 while compare(dt1, dtm): months += increment self._set_months(months) dtm = self.__radd__(dt2) # Get the timedelta between the "months-adjusted" date and dt1 delta = dt1 - dtm self.seconds = delta.seconds + delta.days * 86400 self.microseconds = delta.microseconds else: # Check for non-integer values in integer-only quantities if any(x is not None and x != int(x) for x in (years, months)): raise ValueError("Non-integer years and months are " "ambiguous and not currently supported.") # Relative information self.years = int(years) self.months = int(months) self.days = days + weeks * 7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds # Absolute information self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if any(x is not None and int(x) != x for x in (year, month, day, hour, minute, second, microsecond)): # For now we'll deprecate floats - later it'll be an error. warn("Non-integer value passed as absolute information. " + "This is not a well-defined condition and will raise " + "errors in future versions.", DeprecationWarning) if isinstance(weekday, integer_types): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix()
(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None)
308
dateutil.relativedelta
__mul__
null
def __mul__(self, other): try: f = float(other) except TypeError: return NotImplemented return self.__class__(years=int(self.years * f), months=int(self.months * f), days=int(self.days * f), hours=int(self.hours * f), minutes=int(self.minutes * f), seconds=int(self.seconds * f), microseconds=int(self.microseconds * f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond)
(self, other)
309
dateutil.relativedelta
__ne__
null
def __ne__(self, other): return not self.__eq__(other)
(self, other)
310
dateutil.relativedelta
__neg__
null
def __neg__(self): return self.__class__(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond)
(self)
312
dateutil.relativedelta
__radd__
null
def __radd__(self, other): return self.__add__(other)
(self, other)
313
dateutil.relativedelta
__repr__
null
def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("{attr}={value:+g}".format(attr=attr, value=value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("{attr}={value}".format(attr=attr, value=repr(value))) return "{classname}({attrs})".format(classname=self.__class__.__name__, attrs=", ".join(l))
(self)
315
dateutil.relativedelta
__rsub__
null
def __rsub__(self, other): return self.__neg__().__radd__(other)
(self, other)
316
dateutil.relativedelta
__sub__
null
def __sub__(self, other): if not isinstance(other, relativedelta): return NotImplemented # In case the other object defines __rsub__ return self.__class__(years=self.years - other.years, months=self.months - other.months, days=self.days - other.days, hours=self.hours - other.hours, minutes=self.minutes - other.minutes, seconds=self.seconds - other.seconds, microseconds=self.microseconds - other.microseconds, leapdays=self.leapdays or other.leapdays, year=(self.year if self.year is not None else other.year), month=(self.month if self.month is not None else other.month), day=(self.day if self.day is not None else other.day), weekday=(self.weekday if self.weekday is not None else other.weekday), hour=(self.hour if self.hour is not None else other.hour), minute=(self.minute if self.minute is not None else other.minute), second=(self.second if self.second is not None else other.second), microsecond=(self.microsecond if self.microsecond is not None else other.microsecond))
(self, other)
318
dateutil.relativedelta
_fix
null
def _fix(self): if abs(self.microseconds) > 999999: s = _sign(self.microseconds) div, mod = divmod(self.microseconds * s, 1000000) self.microseconds = mod * s self.seconds += div * s if abs(self.seconds) > 59: s = _sign(self.seconds) div, mod = divmod(self.seconds * s, 60) self.seconds = mod * s self.minutes += div * s if abs(self.minutes) > 59: s = _sign(self.minutes) div, mod = divmod(self.minutes * s, 60) self.minutes = mod * s self.hours += div * s if abs(self.hours) > 23: s = _sign(self.hours) div, mod = divmod(self.hours * s, 24) self.hours = mod * s self.days += div * s if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years += div * s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0
(self)
319
dateutil.relativedelta
_set_months
null
def _set_months(self, months): self.months = months if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years = div * s else: self.years = 0
(self, months)