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
320
dateutil.relativedelta
normalized
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.
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)
(self)
323
datetime
timedelta
Difference between two datetime values. timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.
class timedelta: """Represent the difference between two datetime objects. Supported operators: - add, subtract timedelta - unary plus, minus, abs - compare to timedelta - multiply, divide by int In addition, datetime supports subtraction of two datetime objects returning a timedelta, and addition or subtraction of a datetime and a timedelta giving a datetime. Representation: (days, seconds, microseconds). Why? Because I felt like it. """ __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' def __new__(cls, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): # Doing this efficiently and accurately in C is going to be difficult # and error-prone, due to ubiquitous overflow possibilities, and that # C double doesn't have enough bits of precision to represent # microseconds over 10K years faithfully. The code here tries to make # explicit where go-fast assumptions can be relied on, in order to # guide the C implementation; it's way more convoluted than speed- # ignoring auto-overflow-to-long idiomatic Python could be. # XXX Check that all inputs are ints or floats. # Final values, all integer. # s and us fit in 32-bit signed ints; d isn't bounded. d = s = us = 0 # Normalize everything to days, seconds, microseconds. days += weeks*7 seconds += minutes*60 + hours*3600 microseconds += milliseconds*1000 # Get rid of all fractions, and normalize s and us. # Take a deep breath <wink>. if isinstance(days, float): dayfrac, days = _math.modf(days) daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.)) assert daysecondswhole == int(daysecondswhole) # can't overflow s = int(daysecondswhole) assert days == int(days) d = int(days) else: daysecondsfrac = 0.0 d = days assert isinstance(daysecondsfrac, float) assert abs(daysecondsfrac) <= 1.0 assert isinstance(d, int) assert abs(s) <= 24 * 3600 # days isn't referenced again before redefinition if isinstance(seconds, float): secondsfrac, seconds = _math.modf(seconds) assert seconds == int(seconds) seconds = int(seconds) secondsfrac += daysecondsfrac assert abs(secondsfrac) <= 2.0 else: secondsfrac = daysecondsfrac # daysecondsfrac isn't referenced again assert isinstance(secondsfrac, float) assert abs(secondsfrac) <= 2.0 assert isinstance(seconds, int) days, seconds = divmod(seconds, 24*3600) d += days s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 2 * 24 * 3600 # seconds isn't referenced again before redefinition usdouble = secondsfrac * 1e6 assert abs(usdouble) < 2.1e6 # exact value not critical # secondsfrac isn't referenced again if isinstance(microseconds, float): microseconds = round(microseconds + usdouble) seconds, microseconds = divmod(microseconds, 1000000) days, seconds = divmod(seconds, 24*3600) d += days s += seconds else: microseconds = int(microseconds) seconds, microseconds = divmod(microseconds, 1000000) days, seconds = divmod(seconds, 24*3600) d += days s += seconds microseconds = round(microseconds + usdouble) assert isinstance(s, int) assert isinstance(microseconds, int) assert abs(s) <= 3 * 24 * 3600 assert abs(microseconds) < 3.1e6 # Just a little bit of carrying possible for microseconds and seconds. seconds, us = divmod(microseconds, 1000000) s += seconds days, s = divmod(s, 24*3600) d += days assert isinstance(d, int) assert isinstance(s, int) and 0 <= s < 24*3600 assert isinstance(us, int) and 0 <= us < 1000000 if abs(d) > 999999999: raise OverflowError("timedelta # of days is too large: %d" % d) self = object.__new__(cls) self._days = d self._seconds = s self._microseconds = us self._hashcode = -1 return self def __repr__(self): args = [] if self._days: args.append("days=%d" % self._days) if self._seconds: args.append("seconds=%d" % self._seconds) if self._microseconds: args.append("microseconds=%d" % self._microseconds) if not args: args.append('0') return "%s.%s(%s)" % (self.__class__.__module__, self.__class__.__qualname__, ', '.join(args)) def __str__(self): mm, ss = divmod(self._seconds, 60) hh, mm = divmod(mm, 60) s = "%d:%02d:%02d" % (hh, mm, ss) if self._days: def plural(n): return n, abs(n) != 1 and "s" or "" s = ("%d day%s, " % plural(self._days)) + s if self._microseconds: s = s + ".%06d" % self._microseconds return s def total_seconds(self): """Total seconds in the duration.""" return ((self.days * 86400 + self.seconds) * 10**6 + self.microseconds) / 10**6 # Read-only field accessors @property def days(self): """days""" return self._days @property def seconds(self): """seconds""" return self._seconds @property def microseconds(self): """microseconds""" return self._microseconds def __add__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days + other._days, self._seconds + other._seconds, self._microseconds + other._microseconds) return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days - other._days, self._seconds - other._seconds, self._microseconds - other._microseconds) return NotImplemented def __rsub__(self, other): if isinstance(other, timedelta): return -self + other return NotImplemented def __neg__(self): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(-self._days, -self._seconds, -self._microseconds) def __pos__(self): return self def __abs__(self): if self._days < 0: return -self else: return self def __mul__(self, other): if isinstance(other, int): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days * other, self._seconds * other, self._microseconds * other) if isinstance(other, float): usec = self._to_microseconds() a, b = other.as_integer_ratio() return timedelta(0, 0, _divide_and_round(usec * a, b)) return NotImplemented __rmul__ = __mul__ def _to_microseconds(self): return ((self._days * (24*3600) + self._seconds) * 1000000 + self._microseconds) def __floordiv__(self, other): if not isinstance(other, (int, timedelta)): return NotImplemented usec = self._to_microseconds() if isinstance(other, timedelta): return usec // other._to_microseconds() if isinstance(other, int): return timedelta(0, 0, usec // other) def __truediv__(self, other): if not isinstance(other, (int, float, timedelta)): return NotImplemented usec = self._to_microseconds() if isinstance(other, timedelta): return usec / other._to_microseconds() if isinstance(other, int): return timedelta(0, 0, _divide_and_round(usec, other)) if isinstance(other, float): a, b = other.as_integer_ratio() return timedelta(0, 0, _divide_and_round(b * usec, a)) def __mod__(self, other): if isinstance(other, timedelta): r = self._to_microseconds() % other._to_microseconds() return timedelta(0, 0, r) return NotImplemented def __divmod__(self, other): if isinstance(other, timedelta): q, r = divmod(self._to_microseconds(), other._to_microseconds()) return q, timedelta(0, 0, r) return NotImplemented # Comparisons of timedelta objects with other. def __eq__(self, other): if isinstance(other, timedelta): return self._cmp(other) == 0 else: return NotImplemented def __le__(self, other): if isinstance(other, timedelta): return self._cmp(other) <= 0 else: return NotImplemented def __lt__(self, other): if isinstance(other, timedelta): return self._cmp(other) < 0 else: return NotImplemented def __ge__(self, other): if isinstance(other, timedelta): return self._cmp(other) >= 0 else: return NotImplemented def __gt__(self, other): if isinstance(other, timedelta): return self._cmp(other) > 0 else: return NotImplemented def _cmp(self, other): assert isinstance(other, timedelta) return _cmp(self._getstate(), other._getstate()) def __hash__(self): if self._hashcode == -1: self._hashcode = hash(self._getstate()) return self._hashcode def __bool__(self): return (self._days != 0 or self._seconds != 0 or self._microseconds != 0) # Pickle support. def _getstate(self): return (self._days, self._seconds, self._microseconds) def __reduce__(self): return (self.__class__, self._getstate())
null
324
maya.core
to_iso8601
null
def to_iso8601(dt): return to_utc_offset_naive(dt).isoformat() + 'Z'
(dt)
325
maya.core
to_utc_offset_aware
null
def to_utc_offset_aware(dt): if dt.tzinfo is not None: return dt return pytz.utc.localize(dt)
(dt)
326
maya.core
to_utc_offset_naive
null
def to_utc_offset_naive(dt): if dt.tzinfo is None: return dt return dt.astimezone(pytz.utc).replace(tzinfo=None)
(dt)
327
maya.core
utc_offset
Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If None, use current local time.
def utc_offset(time_struct=None): """ Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If None, use current local time. """ if time_struct: ts = time_struct else: ts = time.localtime() if ts[-1]: offset = time.altzone else: offset = time.timezone return offset
(time_struct=None)
328
maya.core
validate_arguments_type_of_function
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 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
(param_type=None)
329
maya.core
validate_class_type_arguments
Decorator to validate all the arguments to function are of the type of calling class for passed operator
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
(operator)
330
maya.core
when
"Returns a MayaDT instance for the human moment specified. Powered by dateparser. Useful for scraping websites. Examples: 'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015' Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') prefer_dates_from -- what dates are prefered when `string` is ambigous. options are 'past', 'future', and 'current_period' (default: 'current_period'). see: [1] Reference: [1] dateparser.readthedocs.io/en/latest/usage.html#handling-incomplete-dates
def when(string, timezone='UTC', prefer_dates_from='current_period'): """"Returns a MayaDT instance for the human moment specified. Powered by dateparser. Useful for scraping websites. Examples: 'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015' Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') prefer_dates_from -- what dates are prefered when `string` is ambigous. options are 'past', 'future', and 'current_period' (default: 'current_period'). see: [1] Reference: [1] dateparser.readthedocs.io/en/latest/usage.html#handling-incomplete-dates """ settings = { 'TIMEZONE': timezone, 'RETURN_AS_TIMEZONE_AWARE': True, 'TO_TIMEZONE': 'UTC', 'PREFER_DATES_FROM': prefer_dates_from, } dt = dateparser.parse(string, settings=settings) if dt is None: raise ValueError('invalid datetime input specified.') return MayaDT.from_datetime(dt)
(string, timezone='UTC', prefer_dates_from='current_period')
331
funcsigs
BoundArguments
Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: * arguments : OrderedDict An ordered mutable mapping of parameters' names to arguments' values. Does not contain arguments' default values. * signature : Signature The Signature object that created this instance. * args : tuple Tuple of positional arguments values. * kwargs : dict Dict of keyword arguments values.
class BoundArguments(object): '''Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: * arguments : OrderedDict An ordered mutable mapping of parameters' names to arguments' values. Does not contain arguments' default values. * signature : Signature The Signature object that created this instance. * args : tuple Tuple of positional arguments values. * kwargs : dict Dict of keyword arguments values. ''' def __init__(self, signature, arguments): self.arguments = arguments self._signature = signature @property def signature(self): return self._signature @property def args(self): args = [] for param_name, param in self._signature.parameters.items(): if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): # Keyword arguments mapped by 'functools.partial' # (Parameter._partial_kwarg is True) are mapped # in 'BoundArguments.kwargs', along with VAR_KEYWORD & # KEYWORD_ONLY break try: arg = self.arguments[param_name] except KeyError: # We're done here. Other arguments # will be mapped in 'BoundArguments.kwargs' break else: if param.kind == _VAR_POSITIONAL: # *args args.extend(arg) else: # plain argument args.append(arg) return tuple(args) @property def kwargs(self): kwargs = {} kwargs_started = False for param_name, param in self._signature.parameters.items(): if not kwargs_started: if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): kwargs_started = True else: if param_name not in self.arguments: kwargs_started = True continue if not kwargs_started: continue try: arg = self.arguments[param_name] except KeyError: pass else: if param.kind == _VAR_KEYWORD: # **kwargs kwargs.update(arg) else: # plain keyword argument kwargs[param_name] = arg return kwargs def __hash__(self): msg = "unhashable type: '{0}'".format(self.__class__.__name__) raise TypeError(msg) def __eq__(self, other): return (issubclass(other.__class__, BoundArguments) and self.signature == other.signature and self.arguments == other.arguments) def __ne__(self, other): return not self.__eq__(other)
(signature, arguments)
332
funcsigs
__eq__
null
def __eq__(self, other): return (issubclass(other.__class__, BoundArguments) and self.signature == other.signature and self.arguments == other.arguments)
(self, other)
333
funcsigs
__hash__
null
def __hash__(self): msg = "unhashable type: '{0}'".format(self.__class__.__name__) raise TypeError(msg)
(self)
334
funcsigs
__init__
null
def __init__(self, signature, arguments): self.arguments = arguments self._signature = signature
(self, signature, arguments)
337
funcsigs
Parameter
Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is not set. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
class Parameter(object): '''Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is not set. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. ''' __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg') POSITIONAL_ONLY = _POSITIONAL_ONLY POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD VAR_POSITIONAL = _VAR_POSITIONAL KEYWORD_ONLY = _KEYWORD_ONLY VAR_KEYWORD = _VAR_KEYWORD empty = _empty def __init__(self, name, kind, default=_empty, annotation=_empty, _partial_kwarg=False): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{0} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is None: if kind != _POSITIONAL_ONLY: raise ValueError("None is not a valid name for a " "non-positional-only parameter") self._name = name else: name = str(name) if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I): msg = '{0!r} is not a valid parameter name'.format(name) raise ValueError(msg) self._name = name self._partial_kwarg = _partial_kwarg @property def name(self): return self._name @property def default(self): return self._default @property def annotation(self): return self._annotation @property def kind(self): return self._kind def replace(self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg) def __str__(self): kind = self.kind formatted = self._name if kind == _POSITIONAL_ONLY: if formatted is None: formatted = '' formatted = '<{0}>'.format(formatted) # Add annotation and default value if self._annotation is not _empty: formatted = '{0}:{1}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{0}={1}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted def __repr__(self): return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__, id(self), self.name) def __hash__(self): msg = "unhashable type: '{0}'".format(self.__class__.__name__) raise TypeError(msg) def __eq__(self, other): return (issubclass(other.__class__, Parameter) and self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation) def __ne__(self, other): return not self.__eq__(other)
(name, kind, default=<class 'funcsigs._empty'>, annotation=<class 'funcsigs._empty'>, _partial_kwarg=False)
338
funcsigs
__eq__
null
def __eq__(self, other): return (issubclass(other.__class__, Parameter) and self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation)
(self, other)
340
funcsigs
__init__
null
def __init__(self, name, kind, default=_empty, annotation=_empty, _partial_kwarg=False): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{0} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is None: if kind != _POSITIONAL_ONLY: raise ValueError("None is not a valid name for a " "non-positional-only parameter") self._name = name else: name = str(name) if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I): msg = '{0!r} is not a valid parameter name'.format(name) raise ValueError(msg) self._name = name self._partial_kwarg = _partial_kwarg
(self, name, kind, default=<class 'funcsigs._empty'>, annotation=<class 'funcsigs._empty'>, _partial_kwarg=False)
342
funcsigs
__repr__
null
def __repr__(self): return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__, id(self), self.name)
(self)
343
funcsigs
__str__
null
def __str__(self): kind = self.kind formatted = self._name if kind == _POSITIONAL_ONLY: if formatted is None: formatted = '' formatted = '<{0}>'.format(formatted) # Add annotation and default value if self._annotation is not _empty: formatted = '{0}:{1}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{0}={1}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted
(self)
344
funcsigs
replace
Creates a customized copy of the Parameter.
def replace(self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg)
(self, name=<class 'funcsigs._void'>, kind=<class 'funcsigs._void'>, annotation=<class 'funcsigs._void'>, default=<class 'funcsigs._void'>, _partial_kwarg=<class 'funcsigs._void'>)
345
funcsigs
Signature
A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. A Signature object has the following public attributes and methods: * parameters : OrderedDict An ordered mapping of parameters' names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in `code.co_varnames`). * return_annotation : object The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is not set. * bind(*args, **kwargs) -> BoundArguments Creates a mapping from positional and keyword arguments to parameters. * bind_partial(*args, **kwargs) -> BoundArguments Creates a partial mapping from positional and keyword arguments to parameters (simulating 'functools.partial' behavior.)
class Signature(object): '''A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. A Signature object has the following public attributes and methods: * parameters : OrderedDict An ordered mapping of parameters' names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in `code.co_varnames`). * return_annotation : object The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is not set. * bind(*args, **kwargs) -> BoundArguments Creates a mapping from positional and keyword arguments to parameters. * bind_partial(*args, **kwargs) -> BoundArguments Creates a partial mapping from positional and keyword arguments to parameters (simulating 'functools.partial' behavior.) ''' __slots__ = ('_return_annotation', '_parameters') _parameter_cls = Parameter _bound_arguments_cls = BoundArguments empty = _empty def __init__(self, parameters=None, return_annotation=_empty, __validate_parameters__=True): '''Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. ''' if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY for idx, param in enumerate(parameters): kind = param.kind if kind < top_kind: msg = 'wrong parameter order: {0} before {1}' msg = msg.format(top_kind, param.kind) raise ValueError(msg) else: top_kind = kind name = param.name if name is None: name = str(idx) param = param.replace(name=name) if name in params: msg = 'duplicate parameter name: {0!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = params self._return_annotation = return_annotation @classmethod def from_function(cls, func): '''Constructs Signature for the given python function''' if not isinstance(func, types.FunctionType): raise TypeError('{0!r} is not a Python function'.format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = func.__code__ pos_count = func_code.co_argcount arg_names = func_code.co_varnames positional = tuple(arg_names[:pos_count]) keyword_only_count = getattr(func_code, 'co_kwonlyargcount', 0) keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] annotations = getattr(func, '__annotations__', {}) defaults = func.__defaults__ kwdefaults = getattr(func, '__kwdefaults__', None) if defaults: pos_default_count = len(defaults) else: pos_default_count = 0 parameters = [] # Non-keyword-only parameters w/o defaults. non_default_count = pos_count - pos_default_count for name in positional[:non_default_count]: annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD)) # ... w/ defaults. for offset, name in enumerate(positional[non_default_count:]): annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD, default=defaults[offset])) # *args if func_code.co_flags & 0x04: name = arg_names[pos_count + keyword_only_count] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_POSITIONAL)) # Keyword-only parameters. for name in keyword_only: default = _empty if kwdefaults is not None: default = kwdefaults.get(name, _empty) annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_KEYWORD_ONLY, default=default)) # **kwargs if func_code.co_flags & 0x08: index = pos_count + keyword_only_count if func_code.co_flags & 0x04: index += 1 name = arg_names[index] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_KEYWORD)) return cls(parameters, return_annotation=annotations.get('return', _empty), __validate_parameters__=False) @property def parameters(self): try: return types.MappingProxyType(self._parameters) except AttributeError: return OrderedDict(self._parameters.items()) @property def return_annotation(self): return self._return_annotation def replace(self, parameters=_void, return_annotation=_void): '''Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. ''' if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation) def __hash__(self): msg = "unhashable type: '{0}'".format(self.__class__.__name__) raise TypeError(msg) def __eq__(self, other): if (not issubclass(type(other), Signature) or self.return_annotation != other.return_annotation or len(self.parameters) != len(other.parameters)): return False other_positions = dict((param, idx) for idx, param in enumerate(other.parameters.keys())) for idx, (param_name, param) in enumerate(self.parameters.items()): if param.kind == _KEYWORD_ONLY: try: other_param = other.parameters[param_name] except KeyError: return False else: if param != other_param: return False else: try: other_idx = other_positions[param_name] except KeyError: return False else: if (idx != other_idx or param != other.parameters[param_name]): return False return True def __ne__(self, other): return not self.__eq__(other) def _bind(self, args, kwargs, partial=False): '''Private method. Don't use directly.''' arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools.partial' objects. # See 'functools.partial' case in 'signature()' implementation # for details. for param_name, param in self.parameters.items(): if (param._partial_kwarg and param_name not in kwargs): # Simulating 'functools.partial' behavior kwargs[param_name] = param.default while True: # Let's iterate through the positional arguments and corresponding # parameters try: arg_val = next(arg_vals) except StopIteration: # No more positional arguments try: param = next(parameters) except StopIteration: # No more parameters. That's it. Just need to check that # we have no `kwargs` after this while loop break else: if param.kind == _VAR_POSITIONAL: # That's OK, just empty *args. Let's start parsing # kwargs break elif param.name in kwargs: if param.kind == _POSITIONAL_ONLY: msg = '{arg!r} parameter is positional only, ' \ 'but was passed as a keyword' msg = msg.format(arg=param.name) raise TypeError(msg) parameters_ex = (param,) break elif (param.kind == _VAR_KEYWORD or param.default is not _empty): # That's fine too - we have a default value for this # parameter. So, lets start parsing `kwargs`, starting # with the current parameter parameters_ex = (param,) break else: if partial: parameters_ex = (param,) break else: msg = '{arg!r} parameter lacking default value' msg = msg.format(arg=param.name) raise TypeError(msg) else: # We have a positional argument to process try: param = next(parameters) except StopIteration: raise TypeError('too many positional arguments') else: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): # Looks like we have no parameter for this positional # argument raise TypeError('too many positional arguments') if param.kind == _VAR_POSITIONAL: # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase values = [arg_val] values.extend(arg_vals) arguments[param.name] = tuple(values) break if param.name in kwargs: raise TypeError('multiple values for argument ' '{arg!r}'.format(arg=param.name)) arguments[param.name] = arg_val # Now, we iterate through the remaining parameters to process # keyword arguments kwargs_param = None for param in itertools.chain(parameters_ex, parameters): if param.kind == _POSITIONAL_ONLY: # This should never happen in case of a properly built # Signature object (but let's have this check here # to ensure correct behaviour just in case) raise TypeError('{arg!r} parameter is positional only, ' 'but was passed as a keyword'. \ format(arg=param.name)) if param.kind == _VAR_KEYWORD: # Memorize that we have a '**kwargs'-like parameter kwargs_param = param continue param_name = param.name try: arg_val = kwargs.pop(param_name) except KeyError: # We have no value for this parameter. It's fine though, # if it has a default value, or it is an '*args'-like # parameter, left alone by the processing of positional # arguments. if (not partial and param.kind != _VAR_POSITIONAL and param.default is _empty): raise TypeError('{arg!r} parameter lacking default value'. \ format(arg=param_name)) else: arguments[param_name] = arg_val if kwargs: if kwargs_param is not None: # Process our '**kwargs'-like parameter arguments[kwargs_param.name] = kwargs else: raise TypeError('too many keyword arguments %r' % kwargs) return self._bound_arguments_cls(self, arguments) def bind(*args, **kwargs): '''Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return args[0]._bind(args[1:], kwargs) def bind_partial(self, *args, **kwargs): '''Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return self._bind(args, kwargs, partial=True) def __str__(self): result = [] render_kw_only_separator = True for idx, param in enumerate(self.parameters.values()): formatted = str(param) kind = param.kind if kind == _VAR_POSITIONAL: # OK, we have an '*args'-like parameter, so we won't need # a '*' to separate keyword-only arguments render_kw_only_separator = False elif kind == _KEYWORD_ONLY and render_kw_only_separator: # We have a keyword-only parameter to render and we haven't # rendered an '*args'-like parameter before, so add a '*' # separator to the parameters list ("foo(arg1, *, arg2)" case) result.append('*') # This condition should be only triggered once, so # reset the flag render_kw_only_separator = False result.append(formatted) rendered = '({0})'.format(', '.join(result)) if self.return_annotation is not _empty: anno = formatannotation(self.return_annotation) rendered += ' -> {0}'.format(anno) return rendered
(parameters=None, return_annotation=<class 'funcsigs._empty'>, __validate_parameters__=True)
346
funcsigs
__eq__
null
def __eq__(self, other): if (not issubclass(type(other), Signature) or self.return_annotation != other.return_annotation or len(self.parameters) != len(other.parameters)): return False other_positions = dict((param, idx) for idx, param in enumerate(other.parameters.keys())) for idx, (param_name, param) in enumerate(self.parameters.items()): if param.kind == _KEYWORD_ONLY: try: other_param = other.parameters[param_name] except KeyError: return False else: if param != other_param: return False else: try: other_idx = other_positions[param_name] except KeyError: return False else: if (idx != other_idx or param != other.parameters[param_name]): return False return True
(self, other)
348
funcsigs
__init__
Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional.
def __init__(self, parameters=None, return_annotation=_empty, __validate_parameters__=True): '''Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. ''' if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY for idx, param in enumerate(parameters): kind = param.kind if kind < top_kind: msg = 'wrong parameter order: {0} before {1}' msg = msg.format(top_kind, param.kind) raise ValueError(msg) else: top_kind = kind name = param.name if name is None: name = str(idx) param = param.replace(name=name) if name in params: msg = 'duplicate parameter name: {0!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = params self._return_annotation = return_annotation
(self, parameters=None, return_annotation=<class 'funcsigs._empty'>, __validate_parameters__=True)
350
funcsigs
__str__
null
def __str__(self): result = [] render_kw_only_separator = True for idx, param in enumerate(self.parameters.values()): formatted = str(param) kind = param.kind if kind == _VAR_POSITIONAL: # OK, we have an '*args'-like parameter, so we won't need # a '*' to separate keyword-only arguments render_kw_only_separator = False elif kind == _KEYWORD_ONLY and render_kw_only_separator: # We have a keyword-only parameter to render and we haven't # rendered an '*args'-like parameter before, so add a '*' # separator to the parameters list ("foo(arg1, *, arg2)" case) result.append('*') # This condition should be only triggered once, so # reset the flag render_kw_only_separator = False result.append(formatted) rendered = '({0})'.format(', '.join(result)) if self.return_annotation is not _empty: anno = formatannotation(self.return_annotation) rendered += ' -> {0}'.format(anno) return rendered
(self)
351
funcsigs
_bind
Private method. Don't use directly.
def _bind(self, args, kwargs, partial=False): '''Private method. Don't use directly.''' arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools.partial' objects. # See 'functools.partial' case in 'signature()' implementation # for details. for param_name, param in self.parameters.items(): if (param._partial_kwarg and param_name not in kwargs): # Simulating 'functools.partial' behavior kwargs[param_name] = param.default while True: # Let's iterate through the positional arguments and corresponding # parameters try: arg_val = next(arg_vals) except StopIteration: # No more positional arguments try: param = next(parameters) except StopIteration: # No more parameters. That's it. Just need to check that # we have no `kwargs` after this while loop break else: if param.kind == _VAR_POSITIONAL: # That's OK, just empty *args. Let's start parsing # kwargs break elif param.name in kwargs: if param.kind == _POSITIONAL_ONLY: msg = '{arg!r} parameter is positional only, ' \ 'but was passed as a keyword' msg = msg.format(arg=param.name) raise TypeError(msg) parameters_ex = (param,) break elif (param.kind == _VAR_KEYWORD or param.default is not _empty): # That's fine too - we have a default value for this # parameter. So, lets start parsing `kwargs`, starting # with the current parameter parameters_ex = (param,) break else: if partial: parameters_ex = (param,) break else: msg = '{arg!r} parameter lacking default value' msg = msg.format(arg=param.name) raise TypeError(msg) else: # We have a positional argument to process try: param = next(parameters) except StopIteration: raise TypeError('too many positional arguments') else: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): # Looks like we have no parameter for this positional # argument raise TypeError('too many positional arguments') if param.kind == _VAR_POSITIONAL: # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase values = [arg_val] values.extend(arg_vals) arguments[param.name] = tuple(values) break if param.name in kwargs: raise TypeError('multiple values for argument ' '{arg!r}'.format(arg=param.name)) arguments[param.name] = arg_val # Now, we iterate through the remaining parameters to process # keyword arguments kwargs_param = None for param in itertools.chain(parameters_ex, parameters): if param.kind == _POSITIONAL_ONLY: # This should never happen in case of a properly built # Signature object (but let's have this check here # to ensure correct behaviour just in case) raise TypeError('{arg!r} parameter is positional only, ' 'but was passed as a keyword'. \ format(arg=param.name)) if param.kind == _VAR_KEYWORD: # Memorize that we have a '**kwargs'-like parameter kwargs_param = param continue param_name = param.name try: arg_val = kwargs.pop(param_name) except KeyError: # We have no value for this parameter. It's fine though, # if it has a default value, or it is an '*args'-like # parameter, left alone by the processing of positional # arguments. if (not partial and param.kind != _VAR_POSITIONAL and param.default is _empty): raise TypeError('{arg!r} parameter lacking default value'. \ format(arg=param_name)) else: arguments[param_name] = arg_val if kwargs: if kwargs_param is not None: # Process our '**kwargs'-like parameter arguments[kwargs_param.name] = kwargs else: raise TypeError('too many keyword arguments %r' % kwargs) return self._bound_arguments_cls(self, arguments)
(self, args, kwargs, partial=False)
352
funcsigs
bind
Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound.
def bind(*args, **kwargs): '''Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return args[0]._bind(args[1:], kwargs)
(*args, **kwargs)
353
funcsigs
bind_partial
Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound.
def bind_partial(self, *args, **kwargs): '''Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return self._bind(args, kwargs, partial=True)
(self, *args, **kwargs)
354
funcsigs
replace
Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy.
def replace(self, parameters=_void, return_annotation=_void): '''Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. ''' if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation)
(self, parameters=<class 'funcsigs._void'>, return_annotation=<class 'funcsigs._void'>)
355
builtins
method-wrapper
null
method-wrapper
()
356
funcsigs
_ParameterKind
null
class _ParameterKind(int): def __new__(self, *args, **kwargs): obj = int.__new__(self, *args) obj._name = kwargs['name'] return obj def __str__(self): return self._name def __repr__(self): return '<_ParameterKind: {0!r}>'.format(self._name)
(*args, **kwargs)
357
funcsigs
__new__
null
def __new__(self, *args, **kwargs): obj = int.__new__(self, *args) obj._name = kwargs['name'] return obj
(self, *args, **kwargs)
358
funcsigs
__repr__
null
def __repr__(self): return '<_ParameterKind: {0!r}>'.format(self._name)
(self)
359
funcsigs
__str__
null
def __str__(self): return self._name
(self)
360
builtins
wrapper_descriptor
null
from builtins import wrapper_descriptor
()
361
funcsigs
_empty
null
class _empty(object): pass
()
362
funcsigs
_get_user_defined_method
null
def _get_user_defined_method(cls, method_name, *nested): try: if cls is type: return meth = getattr(cls, method_name) for name in nested: meth = getattr(meth, name, meth) except AttributeError: return else: if not isinstance(meth, _NonUserDefinedCallables): # Once '__signature__' will be added to 'C'-level # callables, this check won't be necessary return meth
(cls, method_name, *nested)
363
funcsigs
_void
A private marker - used in Parameter & Signature
class _void(object): '''A private marker - used in Parameter & Signature'''
()
364
funcsigs
formatannotation
null
def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if annotation.__module__ in ('builtins', '__builtin__', base_module): return annotation.__name__ return annotation.__module__+'.'+annotation.__name__ return repr(annotation)
(annotation, base_module=None)
368
funcsigs
signature
Get a signature object for the passed callable.
def signature(obj): '''Get a signature object for the passed callable.''' if not callable(obj): raise TypeError('{0!r} is not a callable object'.format(obj)) if isinstance(obj, types.MethodType): sig = signature(obj.__func__) if obj.__self__ is None: # Unbound method - preserve as-is. return sig else: # Bound method. Eat self - if we can. params = tuple(sig.parameters.values()) if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY): raise ValueError('invalid method signature') kind = params[0].kind if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY): # Drop first parameter: # '(p1, p2[, ...])' -> '(p2[, ...])' params = params[1:] else: if kind is not _VAR_POSITIONAL: # Unless we add a new parameter type we never # get here raise ValueError('invalid argument type') # It's a var-positional parameter. # Do nothing. '(*args[, ...])' -> '(*args[, ...])' return sig.replace(parameters=params) try: sig = obj.__signature__ except AttributeError: pass else: if sig is not None: return sig try: # Was this function wrapped by a decorator? wrapped = obj.__wrapped__ except AttributeError: pass else: return signature(wrapped) if isinstance(obj, types.FunctionType): return Signature.from_function(obj) if isinstance(obj, functools.partial): sig = signature(obj.func) new_params = OrderedDict(sig.parameters.items()) partial_args = obj.args or () partial_keywords = obj.keywords or {} try: ba = sig.bind_partial(*partial_args, **partial_keywords) except TypeError as ex: msg = 'partial object {0!r} has incorrect arguments'.format(obj) raise ValueError(msg) for arg_name, arg_value in ba.arguments.items(): param = new_params[arg_name] if arg_name in partial_keywords: # We set a new default value, because the following code # is correct: # # >>> def foo(a): print(a) # >>> print(partial(partial(foo, a=10), a=20)()) # 20 # >>> print(partial(partial(foo, a=10), a=20)(a=30)) # 30 # # So, with 'partial' objects, passing a keyword argument is # like setting a new default value for the corresponding # parameter # # We also mark this parameter with '_partial_kwarg' # flag. Later, in '_bind', the 'default' value of this # parameter will be added to 'kwargs', to simulate # the 'functools.partial' real call. new_params[arg_name] = param.replace(default=arg_value, _partial_kwarg=True) elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and not param._partial_kwarg): new_params.pop(arg_name) return sig.replace(parameters=new_params.values()) sig = None if isinstance(obj, type): # obj is a class or a metaclass # First, let's see if it has an overloaded __call__ defined # in its metaclass call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) else: # Now we check if the 'obj' class has a '__new__' method new = _get_user_defined_method(obj, '__new__') if new is not None: sig = signature(new) else: # Finally, we should have at least __init__ implemented init = _get_user_defined_method(obj, '__init__') if init is not None: sig = signature(init) elif not isinstance(obj, _NonUserDefinedCallables): # An object with __call__ # We also check that the 'obj' is not an instance of # _WrapperDescriptor or _MethodWrapper to avoid # infinite recursion (and even potential segfault) call = _get_user_defined_method(type(obj), '__call__', 'im_func') if call is not None: sig = signature(call) if sig is not None: # For classes and objects we skip the first parameter of their # __call__, __new__, or __init__ methods return sig.replace(parameters=tuple(sig.parameters.values())[1:]) if isinstance(obj, types.BuiltinFunctionType): # Raise a nicer error message for builtins msg = 'no signature found for builtin function {0!r}'.format(obj) raise ValueError(msg) raise ValueError('callable {0!r} is not supported by signature'.format(obj))
(obj)
371
mohawk.receiver
Receiver
A Hawk authority that will receive and respond to requests. :param credentials_map: Callable to look up the credentials dict by sender ID. The credentials dict must have the keys: ``id``, ``key``, and ``algorithm``. See :ref:`receiving-request` for an example. :type credentials_map: callable :param request_header: A `Hawk`_ ``Authorization`` header such as one created by :class:`mohawk.Sender`. :type request_header: str :param url: Absolute URL of the request. :type url: str :param method: Method of the request. E.G. POST, GET :type method: str :param content=EmptyValue: Byte string of request body. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for request. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow requests that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk
class Receiver(HawkAuthority): """ A Hawk authority that will receive and respond to requests. :param credentials_map: Callable to look up the credentials dict by sender ID. The credentials dict must have the keys: ``id``, ``key``, and ``algorithm``. See :ref:`receiving-request` for an example. :type credentials_map: callable :param request_header: A `Hawk`_ ``Authorization`` header such as one created by :class:`mohawk.Sender`. :type request_header: str :param url: Absolute URL of the request. :type url: str :param method: Method of the request. E.G. POST, GET :type method: str :param content=EmptyValue: Byte string of request body. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for request. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow requests that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk """ #: Value suitable for a ``Server-Authorization`` header. response_header = None def __init__(self, credentials_map, request_header, url, method, content=EmptyValue, content_type=EmptyValue, seen_nonce=None, localtime_offset_in_seconds=0, accept_untrusted_content=False, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): self.response_header = None # make into property that can raise exc? self.credentials_map = credentials_map self.seen_nonce = seen_nonce log.debug('accepting request {header}'.format(header=request_header)) if not request_header: raise MissingAuthorization() parsed_header = parse_authorization_header(request_header) try: credentials = self.credentials_map(parsed_header['id']) except LookupError: etype, val, tb = sys.exc_info() log.debug('Catching {etype}: {val}'.format(etype=etype, val=val)) raise CredentialsLookupError( 'Could not find credentials for ID {0}' .format(parsed_header['id'])) validate_credentials(credentials) resource = Resource(url=url, method=method, ext=parsed_header.get('ext', None), app=parsed_header.get('app', None), dlg=parsed_header.get('dlg', None), credentials=credentials, nonce=parsed_header['nonce'], seen_nonce=self.seen_nonce, content=content, timestamp=parsed_header['ts'], content_type=content_type) self._authorize( 'header', parsed_header, resource, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw) # Now that we verified an incoming request, we can re-use some of its # properties to build our response header. self.parsed_header = parsed_header self.resource = resource def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=EmptyValue: Byte string of response body that will be sent. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for response. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the sender can trust it. :type ext=None: str .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('generating response header') resource = Resource(url=self.resource.url, credentials=self.resource.credentials, ext=ext, app=self.parsed_header.get('app', None), dlg=self.parsed_header.get('dlg', None), method=self.resource.method, content=content, content_type=content_type, always_hash_content=always_hash_content, nonce=self.parsed_header['nonce'], timestamp=self.parsed_header['ts']) mac = calculate_mac('response', resource, resource.gen_content_hash()) self.response_header = self._make_header(resource, mac, additional_keys=['ext']) return self.response_header
(credentials_map, request_header, url, method, content=EmptyValue, content_type=EmptyValue, seen_nonce=None, localtime_offset_in_seconds=0, accept_untrusted_content=False, timestamp_skew_in_seconds=60, **auth_kw)
372
mohawk.receiver
__init__
null
def __init__(self, credentials_map, request_header, url, method, content=EmptyValue, content_type=EmptyValue, seen_nonce=None, localtime_offset_in_seconds=0, accept_untrusted_content=False, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): self.response_header = None # make into property that can raise exc? self.credentials_map = credentials_map self.seen_nonce = seen_nonce log.debug('accepting request {header}'.format(header=request_header)) if not request_header: raise MissingAuthorization() parsed_header = parse_authorization_header(request_header) try: credentials = self.credentials_map(parsed_header['id']) except LookupError: etype, val, tb = sys.exc_info() log.debug('Catching {etype}: {val}'.format(etype=etype, val=val)) raise CredentialsLookupError( 'Could not find credentials for ID {0}' .format(parsed_header['id'])) validate_credentials(credentials) resource = Resource(url=url, method=method, ext=parsed_header.get('ext', None), app=parsed_header.get('app', None), dlg=parsed_header.get('dlg', None), credentials=credentials, nonce=parsed_header['nonce'], seen_nonce=self.seen_nonce, content=content, timestamp=parsed_header['ts'], content_type=content_type) self._authorize( 'header', parsed_header, resource, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw) # Now that we verified an incoming request, we can re-use some of its # properties to build our response header. self.parsed_header = parsed_header self.resource = resource
(self, credentials_map, request_header, url, method, content=EmptyValue, content_type=EmptyValue, seen_nonce=None, localtime_offset_in_seconds=0, accept_untrusted_content=False, timestamp_skew_in_seconds=60, **auth_kw)
373
mohawk.base
_authorize
null
def _authorize(self, mac_type, parsed_header, resource, their_timestamp=None, timestamp_skew_in_seconds=default_ts_skew_in_seconds, localtime_offset_in_seconds=0, accept_untrusted_content=False): now = utc_now(offset_in_seconds=localtime_offset_in_seconds) their_hash = parsed_header.get('hash', '') their_mac = parsed_header.get('mac', '') mac = calculate_mac(mac_type, resource, their_hash) if not strings_match(mac, their_mac): raise MacMismatch('MACs do not match; ours: {ours}; ' 'theirs: {theirs}' .format(ours=mac, theirs=their_mac)) check_hash = True if 'hash' not in parsed_header: # The request did not hash its content. if not resource.content and not resource.content_type: # It is acceptable to not receive a hash if there is no content # to hash. log.debug('NOT calculating/verifying payload hash ' '(no hash in header, request body is empty)') check_hash = False elif accept_untrusted_content: # Allow the request, even if it has content. Missing content or # content_type values will be coerced to the empty string for # hashing purposes. log.debug('NOT calculating/verifying payload hash ' '(no hash in header, accept_untrusted_content=True)') check_hash = False if check_hash: if not their_hash: log.info('request unexpectedly did not hash its content') content_hash = resource.gen_content_hash() if not strings_match(content_hash, their_hash): # The hash declared in the header is incorrect. # Content could have been tampered with. log.debug('mismatched content: {content}' .format(content=repr(resource.content))) log.debug('mismatched content-type: {typ}' .format(typ=repr(resource.content_type))) raise MisComputedContentHash( 'Our hash {ours} ({algo}) did not ' 'match theirs {theirs}' .format(ours=content_hash, theirs=their_hash, algo=resource.credentials['algorithm'])) if resource.seen_nonce: if resource.seen_nonce(resource.credentials['id'], parsed_header['nonce'], parsed_header['ts']): raise AlreadyProcessed('Nonce {nonce} with timestamp {ts} ' 'has already been processed for {id}' .format(nonce=parsed_header['nonce'], ts=parsed_header['ts'], id=resource.credentials['id'])) else: log.warning('seen_nonce was None; not checking nonce. ' 'You may be vulnerable to replay attacks') their_ts = int(their_timestamp or parsed_header['ts']) if math.fabs(their_ts - now) > timestamp_skew_in_seconds: message = ('token with UTC timestamp {ts} has expired; ' 'it was compared to {now}' .format(ts=their_ts, now=now)) tsm = calculate_ts_mac(now, resource.credentials) if isinstance(tsm, six.binary_type): tsm = tsm.decode('ascii') www_authenticate = ('Hawk ts="{ts}", tsm="{tsm}", error="{error}"' .format(ts=now, tsm=tsm, error=message)) raise TokenExpired(message, localtime_in_seconds=now, www_authenticate=www_authenticate) log.debug('authorized OK')
(self, mac_type, parsed_header, resource, their_timestamp=None, timestamp_skew_in_seconds=60, localtime_offset_in_seconds=0, accept_untrusted_content=False)
374
mohawk.base
_make_header
null
def _make_header(self, resource, mac, additional_keys=None): keys = additional_keys if not keys: # These are the default header keys that you'd send with a # request header. Response headers are odd because they # exclude a bunch of keys. keys = ('id', 'ts', 'nonce', 'ext', 'app', 'dlg') header = u'Hawk mac="{mac}"'.format(mac=prepare_header_val(mac)) if resource.content_hash: header = u'{header}, hash="{hash}"'.format( header=header, hash=prepare_header_val(resource.content_hash)) if 'id' in keys: header = u'{header}, id="{id}"'.format( header=header, id=prepare_header_val(resource.credentials['id'])) if 'ts' in keys: header = u'{header}, ts="{ts}"'.format( header=header, ts=prepare_header_val(resource.timestamp)) if 'nonce' in keys: header = u'{header}, nonce="{nonce}"'.format( header=header, nonce=prepare_header_val(resource.nonce)) # These are optional so we need to check if they have values first. if 'ext' in keys and resource.ext: header = u'{header}, ext="{ext}"'.format( header=header, ext=prepare_header_val(resource.ext)) if 'app' in keys and resource.app: header = u'{header}, app="{app}"'.format( header=header, app=prepare_header_val(resource.app)) if 'dlg' in keys and resource.dlg: header = u'{header}, dlg="{dlg}"'.format( header=header, dlg=prepare_header_val(resource.dlg)) log.debug('Hawk header for URL={url} method={method}: {header}' .format(url=resource.url, method=resource.method, header=header)) return header
(self, resource, mac, additional_keys=None)
375
mohawk.receiver
respond
Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=EmptyValue: Byte string of response body that will be sent. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for response. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the sender can trust it. :type ext=None: str .. _`Hawk`: https://github.com/hueniverse/hawk
def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=EmptyValue: Byte string of response body that will be sent. :type content=EmptyValue: str :param content_type=EmptyValue: content-type header value for response. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the sender can trust it. :type ext=None: str .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('generating response header') resource = Resource(url=self.resource.url, credentials=self.resource.credentials, ext=ext, app=self.parsed_header.get('app', None), dlg=self.parsed_header.get('dlg', None), method=self.resource.method, content=content, content_type=content_type, always_hash_content=always_hash_content, nonce=self.parsed_header['nonce'], timestamp=self.parsed_header['ts']) mac = calculate_mac('response', resource, resource.gen_content_hash()) self.response_header = self._make_header(resource, mac, additional_keys=['ext']) return self.response_header
(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None)
376
mohawk.sender
Sender
A Hawk authority that will emit requests and verify responses. :param credentials: Dict of credentials with keys ``id``, ``key``, and ``algorithm``. See :ref:`usage` for an example. :type credentials: dict :param url: Absolute URL of the request. :type url: str :param method: Method of the request. E.G. POST, GET :type method: str :param content=EmptyValue: Byte string of request body or a file-like object. :type content=EmptyValue: str or file-like object :param content_type=EmptyValue: content-type header value for request. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param nonce=None: A string that when coupled with the timestamp will uniquely identify this request to prevent replays. If None, a nonce will be generated for you. :type nonce=None: str :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the receiver can trust it. :type ext=None: str :param app=None: A `Hawk`_ application string. If not None, this value will be signed so that the receiver can trust it. :type app=None: str :param dlg=None: A `Hawk`_ delegation string. If not None, this value will be signed so that the receiver can trust it. :type dlg=None: str :param seen_nonce=None: A callable that returns True if a nonce has been seen. See :ref:`nonce` for details. :type seen_nonce=None: callable .. _`Hawk`: https://github.com/hueniverse/hawk
class Sender(HawkAuthority): """ A Hawk authority that will emit requests and verify responses. :param credentials: Dict of credentials with keys ``id``, ``key``, and ``algorithm``. See :ref:`usage` for an example. :type credentials: dict :param url: Absolute URL of the request. :type url: str :param method: Method of the request. E.G. POST, GET :type method: str :param content=EmptyValue: Byte string of request body or a file-like object. :type content=EmptyValue: str or file-like object :param content_type=EmptyValue: content-type header value for request. :type content_type=EmptyValue: str :param always_hash_content=True: When True, ``content`` and ``content_type`` must be provided. Read :ref:`skipping-content-checks` to learn more. :type always_hash_content=True: bool :param nonce=None: A string that when coupled with the timestamp will uniquely identify this request to prevent replays. If None, a nonce will be generated for you. :type nonce=None: str :param ext=None: An external `Hawk`_ string. If not None, this value will be signed so that the receiver can trust it. :type ext=None: str :param app=None: A `Hawk`_ application string. If not None, this value will be signed so that the receiver can trust it. :type app=None: str :param dlg=None: A `Hawk`_ delegation string. If not None, this value will be signed so that the receiver can trust it. :type dlg=None: str :param seen_nonce=None: A callable that returns True if a nonce has been seen. See :ref:`nonce` for details. :type seen_nonce=None: callable .. _`Hawk`: https://github.com/hueniverse/hawk """ #: Value suitable for an ``Authorization`` header. request_header = None def __init__(self, credentials, url, method, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, nonce=None, ext=None, app=None, dlg=None, seen_nonce=None, # For easier testing: _timestamp=None): self.reconfigure(credentials) self.request_header = None self.seen_nonce = seen_nonce log.debug('generating request header') self.req_resource = Resource(url=url, credentials=self.credentials, ext=ext, app=app, dlg=dlg, nonce=nonce, method=method, content=content, always_hash_content=always_hash_content, timestamp=_timestamp, content_type=content_type) mac = calculate_mac('header', self.req_resource, self.req_resource.gen_content_hash()) self.request_header = self._make_header(self.req_resource, mac) def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): """ Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('accepting response {header}' .format(header=response_header)) parsed_header = parse_authorization_header(response_header) resource = Resource(ext=parsed_header.get('ext', None), content=content, content_type=content_type, # The following response attributes are # in reference to the original request, # not to the reponse header: timestamp=self.req_resource.timestamp, nonce=self.req_resource.nonce, url=self.req_resource.url, method=self.req_resource.method, app=self.req_resource.app, dlg=self.req_resource.dlg, credentials=self.credentials, seen_nonce=self.seen_nonce) self._authorize( 'response', parsed_header, resource, # Per Node lib, a responder macs the *sender's* timestamp. # It does not create its own timestamp. # I suppose a slow response could time out here. Maybe only check # mac failures, not timeouts? their_timestamp=resource.timestamp, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw) def reconfigure(self, credentials): validate_credentials(credentials) self.credentials = credentials
(credentials, url, method, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, nonce=None, ext=None, app=None, dlg=None, seen_nonce=None, _timestamp=None)
377
mohawk.sender
__init__
null
def __init__(self, credentials, url, method, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, nonce=None, ext=None, app=None, dlg=None, seen_nonce=None, # For easier testing: _timestamp=None): self.reconfigure(credentials) self.request_header = None self.seen_nonce = seen_nonce log.debug('generating request header') self.req_resource = Resource(url=url, credentials=self.credentials, ext=ext, app=app, dlg=dlg, nonce=nonce, method=method, content=content, always_hash_content=always_hash_content, timestamp=_timestamp, content_type=content_type) mac = calculate_mac('header', self.req_resource, self.req_resource.gen_content_hash()) self.request_header = self._make_header(self.req_resource, mac)
(self, credentials, url, method, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, nonce=None, ext=None, app=None, dlg=None, seen_nonce=None, _timestamp=None)
380
mohawk.sender
accept_response
Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): """ Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('accepting response {header}' .format(header=response_header)) parsed_header = parse_authorization_header(response_header) resource = Resource(ext=parsed_header.get('ext', None), content=content, content_type=content_type, # The following response attributes are # in reference to the original request, # not to the reponse header: timestamp=self.req_resource.timestamp, nonce=self.req_resource.nonce, url=self.req_resource.url, method=self.req_resource.method, app=self.req_resource.app, dlg=self.req_resource.dlg, credentials=self.credentials, seen_nonce=self.seen_nonce) self._authorize( 'response', parsed_header, resource, # Per Node lib, a responder macs the *sender's* timestamp. # It does not create its own timestamp. # I suppose a slow response could time out here. Maybe only check # mac failures, not timeouts? their_timestamp=resource.timestamp, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw)
(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=60, **auth_kw)
381
mohawk.sender
reconfigure
null
def reconfigure(self, credentials): validate_credentials(credentials) self.credentials = credentials
(self, credentials)
390
tufup
main
null
def main(args=None): # show version before anything else print(f'tufup {__version__}') # default to --help if args is None: args = sys.argv[1:] or ['--help'] # parse command line arguments options = cli.get_parser().parse_args(args=args) # exit if version is requested (printed above) if options.version: return # cli debugging if options.debug: logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, force=True) # process command try: options.func(options) except Exception: # noqa logger.exception(f'Failed to process command: {args}')
(args=None)
394
bitmath
Bit
Bit based types fundamentally operate on self._bit_value
class Bit(Bitmath): """Bit based types fundamentally operate on self._bit_value""" def _set_prefix_value(self): self.prefix_value = self._to_prefix_value(self._bit_value) def _setup(self): return (2, 0, 'Bit', 'Bits') def _norm(self, value): """Normalize the input value into the fundamental unit for this prefix type""" self._bit_value = value * self._unit_value self._byte_value = self._bit_value / 8.0
(value=0, bytes=None, bits=None)
395
bitmath
__abs__
null
def __abs__(self): return (type(self))(abs(self.prefix_value))
(self)
396
bitmath
__add__
Supported operations with result types: - bm + bm = bm - bm + num = num - num + bm = num (see radd)
def __add__(self, other): """Supported operations with result types: - bm + bm = bm - bm + num = num - num + bm = num (see radd) """ if isinstance(other, numbers.Number): # bm + num return other + self.value else: # bm + bm total_bytes = self._byte_value + other.bytes return (type(self))(bytes=total_bytes)
(self, other)
397
bitmath
__and__
"Bitwise and, ex: 100 & 2 bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
def __and__(self, other): """"Bitwise and, ex: 100 & 2 bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.""" andd = int(self.bits) & other return type(self)(bits=andd)
(self, other)
398
bitmath
__div__
Division: Supported operations with result types: - bm1 / bm2 = num - bm / num = bm - num / bm = num (see rdiv)
def __div__(self, other): """Division: Supported operations with result types: - bm1 / bm2 = num - bm / num = bm - num / bm = num (see rdiv) """ if isinstance(other, numbers.Number): # bm / num result = self._byte_value / other return (type(self))(bytes=result) else: # bm1 / bm2 return self._byte_value / float(other.bytes)
(self, other)
399
bitmath
__eq__
null
def __eq__(self, other): if isinstance(other, numbers.Number): return self.prefix_value == other else: return self._byte_value == other.bytes
(self, other)
400
bitmath
__float__
Return this instances prefix unit as a floating point number
def __float__(self): """Return this instances prefix unit as a floating point number""" return float(self.prefix_value)
(self)
401
bitmath
__ge__
null
def __ge__(self, other): if isinstance(other, numbers.Number): return self.prefix_value >= other else: return self._byte_value >= other.bytes
(self, other)
402
bitmath
__gt__
null
def __gt__(self, other): if isinstance(other, numbers.Number): return self.prefix_value > other else: return self._byte_value > other.bytes
(self, other)
403
bitmath
__init__
Instantiate with `value` by the unit, in plain bytes, or bits. Don't supply more than one keyword. default behavior: initialize with value of 0 only setting value: assert bytes is None and bits is None only setting bytes: assert value == 0 and bits is None only setting bits: assert value == 0 and bytes is None
def __init__(self, value=0, bytes=None, bits=None): """Instantiate with `value` by the unit, in plain bytes, or bits. Don't supply more than one keyword. default behavior: initialize with value of 0 only setting value: assert bytes is None and bits is None only setting bytes: assert value == 0 and bits is None only setting bits: assert value == 0 and bytes is None """ _raise = False if (value == 0) and (bytes is None) and (bits is None): pass # Setting by bytes elif bytes is not None: if (value == 0) and (bits is None): pass else: _raise = True # setting by bits elif bits is not None: if (value == 0) and (bytes is None): pass else: _raise = True if _raise: raise ValueError("Only one parameter of: value, bytes, or bits is allowed") self._do_setup() if bytes: # We were provided with the fundamental base unit, no need # to normalize self._byte_value = bytes self._bit_value = bytes * 8.0 elif bits: # We were *ALMOST* given the fundamental base # unit. Translate it into the fundamental unit then # normalize. self._byte_value = bits / 8.0 self._bit_value = bits else: # We were given a value representative of this *prefix # unit*. We need to normalize it into the number of bytes # it represents. self._norm(value) # We have the fundamental unit figured out. Set the 'pretty' unit self._set_prefix_value()
(self, value=0, bytes=None, bits=None)
404
bitmath
__int__
Return this instances prefix unit as an integer
def __int__(self): """Return this instances prefix unit as an integer""" return int(self.prefix_value)
(self)
405
bitmath
__le__
null
def __le__(self, other): if isinstance(other, numbers.Number): return self.prefix_value <= other else: return self._byte_value <= other.bytes
(self, other)
406
bitmath
__long__
Return this instances prefix unit as a long integer
def __long__(self): """Return this instances prefix unit as a long integer""" return long(self.prefix_value) # pragma: PY3X no cover
(self)
407
bitmath
__lshift__
Left shift, ex: 100 << 2 A left shift by n bits is equivalent to multiplication by pow(2, n). A long integer is returned if the result exceeds the range of plain integers.
def __lshift__(self, other): """Left shift, ex: 100 << 2 A left shift by n bits is equivalent to multiplication by pow(2, n). A long integer is returned if the result exceeds the range of plain integers.""" shifted = int(self.bits) << other return type(self)(bits=shifted)
(self, other)
408
bitmath
__lt__
null
def __lt__(self, other): if isinstance(other, numbers.Number): return self.prefix_value < other else: return self._byte_value < other.bytes
(self, other)
409
bitmath
__mul__
Multiplication: Supported operations with result types: - bm1 * bm2 = bm1 - bm * num = bm - num * bm = num (see rmul)
def __mul__(self, other): """Multiplication: Supported operations with result types: - bm1 * bm2 = bm1 - bm * num = bm - num * bm = num (see rmul) """ if isinstance(other, numbers.Number): # bm * num result = self._byte_value * other return (type(self))(bytes=result) else: # bm1 * bm2 _other = other.value * other.base ** other.power _self = self.prefix_value * self._base ** self._power return (type(self))(bytes=_other * _self)
(self, other)
410
bitmath
__ne__
null
def __ne__(self, other): if isinstance(other, numbers.Number): return self.prefix_value != other else: return self._byte_value != other.bytes
(self, other)
411
bitmath
__neg__
The negative version of this instance
def __neg__(self): """The negative version of this instance""" return (type(self))(-abs(self.prefix_value))
(self)
412
bitmath
__or__
Bitwise or, ex: 100 | 2 Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
def __or__(self, other): """Bitwise or, ex: 100 | 2 Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.""" ord = int(self.bits) | other return type(self)(bits=ord)
(self, other)
413
bitmath
__pos__
null
def __pos__(self): return (type(self))(abs(self.prefix_value))
(self)
414
bitmath
__radd__
null
def __radd__(self, other): # num + bm = num return other + self.value
(self, other)
415
bitmath
__rdiv__
null
def __rdiv__(self, other): # num / bm = num return other / float(self.value)
(self, other)
416
bitmath
__repr__
Representation of this object as you would expect to see in an interpreter
def __repr__(self): """Representation of this object as you would expect to see in an interpreter""" global _FORMAT_REPR return self.format(_FORMAT_REPR)
(self)
417
bitmath
__rmul__
null
def __rmul__(self, other): # num * bm = bm return self * other
(self, other)
418
bitmath
__rshift__
Right shift, ex: 100 >> 2 A right shift by n bits is equivalent to division by pow(2, n).
def __rshift__(self, other): """Right shift, ex: 100 >> 2 A right shift by n bits is equivalent to division by pow(2, n).""" shifted = int(self.bits) >> other return type(self)(bits=shifted)
(self, other)
419
bitmath
__rsub__
null
def __rsub__(self, other): # num - bm = num return other - self.value
(self, other)
420
bitmath
__rtruediv__
null
def __rtruediv__(self, other): # num / bm = num return other / float(self.value)
(self, other)
421
bitmath
__str__
String representation of this object
def __str__(self): """String representation of this object""" global format_string return self.format(format_string)
(self)
422
bitmath
__sub__
Subtraction: Supported operations with result types: - bm - bm = bm - bm - num = num - num - bm = num (see rsub)
def __sub__(self, other): """Subtraction: Supported operations with result types: - bm - bm = bm - bm - num = num - num - bm = num (see rsub) """ if isinstance(other, numbers.Number): # bm - num return self.value - other else: # bm - bm total_bytes = self._byte_value - other.bytes return (type(self))(bytes=total_bytes)
(self, other)
423
bitmath
__truediv__
null
def __truediv__(self, other): # num / bm return self.__div__(other)
(self, other)
424
bitmath
__xor__
Bitwise xor, ex: 100 ^ 2 Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
def __xor__(self, other): """Bitwise xor, ex: 100 ^ 2 Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.""" xord = int(self.bits) ^ other return type(self)(bits=xord)
(self, other)
425
bitmath
_do_setup
Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the corresponding prefix. I.e., base=2, power=10 represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte. Likewise, for the SI prefix classes `base` will be 10, and the `power` for the Kilobyte is 3.
def _do_setup(self): """Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the corresponding prefix. I.e., base=2, power=10 represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte. Likewise, for the SI prefix classes `base` will be 10, and the `power` for the Kilobyte is 3. """ (self._base, self._power, self._name_singular, self._name_plural) = self._setup() self._unit_value = self._base ** self._power
(self)
426
bitmath
_norm
Normalize the input value into the fundamental unit for this prefix type
def _norm(self, value): """Normalize the input value into the fundamental unit for this prefix type""" self._bit_value = value * self._unit_value self._byte_value = self._bit_value / 8.0
(self, value)
427
bitmath
_set_prefix_value
null
def _set_prefix_value(self): self.prefix_value = self._to_prefix_value(self._bit_value)
(self)
428
bitmath
_setup
null
def _setup(self): return (2, 0, 'Bit', 'Bits')
(self)
429
bitmath
_to_prefix_value
Return the number of bits/bytes as they would look like if we converted *to* this unit
def _to_prefix_value(self, value): """Return the number of bits/bytes as they would look like if we converted *to* this unit""" return value / float(self._unit_value)
(self, value)
430
bitmath
best_prefix
Optional parameter, `system`, allows you to prefer NIST or SI in the results. By default, the current system is used (Bit/Byte default to NIST). Logic discussion/notes: Base-case, does it need converting? If the instance is less than one Byte, return the instance as a Bit instance. Else, begin by recording the unit system the instance is defined by. This determines which steps (NIST_STEPS/SI_STEPS) we iterate over. If the instance is not already a ``Byte`` instance, convert it to one. NIST units step up by powers of 1024, SI units step up by powers of 1000. Take integer value of the log(base=STEP_POWER) of the instance's byte value. E.g.: >>> int(math.log(Gb(100).bytes, 1000)) 3 This will return a value >= 0. The following determines the 'best prefix unit' for representation: * result == 0, best represented as a Byte * result >= len(SYSTEM_STEPS), best represented as an Exbi/Exabyte * 0 < result < len(SYSTEM_STEPS), best represented as SYSTEM_PREFIXES[result-1]
def best_prefix(self, system=None): """Optional parameter, `system`, allows you to prefer NIST or SI in the results. By default, the current system is used (Bit/Byte default to NIST). Logic discussion/notes: Base-case, does it need converting? If the instance is less than one Byte, return the instance as a Bit instance. Else, begin by recording the unit system the instance is defined by. This determines which steps (NIST_STEPS/SI_STEPS) we iterate over. If the instance is not already a ``Byte`` instance, convert it to one. NIST units step up by powers of 1024, SI units step up by powers of 1000. Take integer value of the log(base=STEP_POWER) of the instance's byte value. E.g.: >>> int(math.log(Gb(100).bytes, 1000)) 3 This will return a value >= 0. The following determines the 'best prefix unit' for representation: * result == 0, best represented as a Byte * result >= len(SYSTEM_STEPS), best represented as an Exbi/Exabyte * 0 < result < len(SYSTEM_STEPS), best represented as SYSTEM_PREFIXES[result-1] """ # Use absolute value so we don't return Bit's for *everything* # less than Byte(1). From github issue #55 if abs(self) < Byte(1): return Bit.from_other(self) else: if type(self) is Byte: # pylint: disable=unidiomatic-typecheck _inst = self else: _inst = Byte.from_other(self) # Which table to consult? Was a preferred system provided? if system is None: # No preference. Use existing system if self.system == 'NIST': _STEPS = NIST_PREFIXES _BASE = 1024 elif self.system == 'SI': _STEPS = SI_PREFIXES _BASE = 1000 # Anything else would have raised by now else: # Preferred system provided. if system == NIST: _STEPS = NIST_PREFIXES _BASE = 1024 elif system == SI: _STEPS = SI_PREFIXES _BASE = 1000 else: raise ValueError("Invalid value given for 'system' parameter." " Must be one of NIST or SI") # Index of the string of the best prefix in the STEPS list _index = int(math.log(abs(_inst.bytes), _BASE)) # Recall that the log() function returns >= 0. This doesn't # map to the STEPS list 1:1. That is to say, 0 is handled with # special care. So if the _index is 1, we actually want item 0 # in the list. if _index == 0: # Already a Byte() type, so return it. return _inst elif _index >= len(_STEPS): # This is a really big number. Use the biggest prefix we've got _best_prefix = _STEPS[-1] elif 0 < _index < len(_STEPS): # There is an appropriate prefix unit to represent this _best_prefix = _STEPS[_index - 1] _conversion_method = getattr( self, 'to_%sB' % _best_prefix) return _conversion_method()
(self, system=None)
431
bitmath
format
Return a representation of this instance formatted with user supplied syntax
def format(self, fmt): """Return a representation of this instance formatted with user supplied syntax""" _fmt_params = { 'base': self.base, 'bin': self.bin, 'binary': self.binary, 'bits': self.bits, 'bytes': self.bytes, 'power': self.power, 'system': self.system, 'unit': self.unit, 'unit_plural': self.unit_plural, 'unit_singular': self.unit_singular, 'value': self.value } return fmt.format(**_fmt_params)
(self, fmt)
432
bitmath
to_Bit
null
def to_Bit(self): return Bit(self._bit_value)
(self)
433
bitmath
to_Byte
null
def to_Byte(self): return Byte(self._byte_value / float(NIST_STEPS['Byte']))
(self)
434
bitmath
to_EB
null
def to_EB(self): return EB(bits=self._bit_value)
(self)
435
bitmath
to_Eb
null
def to_Eb(self): return Eb(bits=self._bit_value)
(self)
436
bitmath
to_EiB
null
def to_EiB(self): return EiB(bits=self._bit_value)
(self)
437
bitmath
to_Eib
null
def to_Eib(self): return Eib(bits=self._bit_value)
(self)
438
bitmath
to_GB
null
def to_GB(self): return GB(bits=self._bit_value)
(self)
439
bitmath
to_Gb
null
def to_Gb(self): return Gb(bits=self._bit_value)
(self)
440
bitmath
to_GiB
null
def to_GiB(self): return GiB(bits=self._bit_value)
(self)
441
bitmath
to_Gib
null
def to_Gib(self): return Gib(bits=self._bit_value)
(self)
442
bitmath
to_KiB
null
def to_KiB(self): return KiB(bits=self._bit_value)
(self)
443
bitmath
to_Kib
null
def to_Kib(self): return Kib(bits=self._bit_value)
(self)
444
bitmath
to_MB
null
def to_MB(self): return MB(bits=self._bit_value)
(self)
445
bitmath
to_Mb
null
def to_Mb(self): return Mb(bits=self._bit_value)
(self)