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
446
bitmath
to_MiB
null
def to_MiB(self): return MiB(bits=self._bit_value)
(self)
447
bitmath
to_Mib
null
def to_Mib(self): return Mib(bits=self._bit_value)
(self)
448
bitmath
to_PB
null
def to_PB(self): return PB(bits=self._bit_value)
(self)
449
bitmath
to_Pb
null
def to_Pb(self): return Pb(bits=self._bit_value)
(self)
450
bitmath
to_PiB
null
def to_PiB(self): return PiB(bits=self._bit_value)
(self)
451
bitmath
to_Pib
null
def to_Pib(self): return Pib(bits=self._bit_value)
(self)
452
bitmath
to_TB
null
def to_TB(self): return TB(bits=self._bit_value)
(self)
453
bitmath
to_Tb
null
def to_Tb(self): return Tb(bits=self._bit_value)
(self)
454
bitmath
to_TiB
null
def to_TiB(self): return TiB(bits=self._bit_value)
(self)
455
bitmath
to_Tib
null
def to_Tib(self): return Tib(bits=self._bit_value)
(self)
456
bitmath
to_YB
null
def to_YB(self): return YB(bits=self._bit_value)
(self)
457
bitmath
to_Yb
null
def to_Yb(self): return Yb(bits=self._bit_value)
(self)
458
bitmath
to_ZB
null
def to_ZB(self): return ZB(bits=self._bit_value)
(self)
459
bitmath
to_Zb
null
def to_Zb(self): return Zb(bits=self._bit_value)
(self)
460
bitmath
to_kB
null
def to_kB(self): return kB(bits=self._bit_value)
(self)
461
bitmath
to_kb
null
def to_kb(self): return kb(bits=self._bit_value)
(self)
462
bitmath
Bitmath
The base class for all the other prefix classes
class Bitmath(object): """The base class for all the other prefix classes""" # All the allowed input types valid_types = (int, float, long) 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() def _set_prefix_value(self): self.prefix_value = self._to_prefix_value(self._byte_value) 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) def _setup(self): raise NotImplementedError("The base 'bitmath.Bitmath' class can not be used directly") 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 def _norm(self, value): """Normalize the input value into the fundamental unit for this prefix type. :param number value: The input value to be normalized :raises ValueError: if the input value is not a type of real number """ if isinstance(value, self.valid_types): self._byte_value = value * self._unit_value self._bit_value = self._byte_value * 8.0 else: raise ValueError("Initialization value '%s' is of an invalid type: %s. " "Must be one of %s" % ( value, type(value), ", ".join(str(x) for x in self.valid_types))) ################################################################## # Properties #: The mathematical base of an instance base = property(lambda s: s._base) binary = property(lambda s: bin(int(s.bits))) """The binary representation of an instance in binary 1s and 0s. Note that for very large numbers this will mean a lot of 1s and 0s. For example, GiB(100) would be represented as:: 0b1100100000000000000000000000000000000000 That leading ``0b`` is normal. That's how Python represents binary. """ #: Alias for :attr:`binary` bin = property(lambda s: s.binary) #: The number of bits in an instance bits = property(lambda s: s._bit_value) #: The number of bytes in an instance bytes = property(lambda s: s._byte_value) #: The mathematical power of an instance power = property(lambda s: s._power) @property def system(self): """The system of units used to measure an instance""" if self._base == 2: return "NIST" elif self._base == 10: return "SI" else: # I don't expect to ever encounter this logic branch, but # hey, it's better to have extra test coverage than # insufficient test coverage. raise ValueError("Instances mathematical base is an unsupported value: %s" % ( str(self._base))) @property def unit(self): """The string that is this instances prefix unit name in agreement with this instance value (singular or plural). Following the convention that only 1 is singular. This will always be the singular form when :attr:`bitmath.format_plural` is ``False`` (default value). For example: >>> KiB(1).unit == 'KiB' >>> Byte(0).unit == 'Bytes' >>> Byte(1).unit == 'Byte' >>> Byte(1.1).unit == 'Bytes' >>> Gb(2).unit == 'Gbs' """ global format_plural if self.prefix_value == 1: # If it's a '1', return it singular, no matter what return self._name_singular elif format_plural: # Pluralization requested return self._name_plural else: # Pluralization NOT requested, and the value is not 1 return self._name_singular @property def unit_plural(self): """The string that is an instances prefix unit name in the plural form. For example: >>> KiB(1).unit_plural == 'KiB' >>> Byte(1024).unit_plural == 'Bytes' >>> Gb(1).unit_plural == 'Gb' """ return self._name_plural @property def unit_singular(self): """The string that is an instances prefix unit name in the singular form. For example: >>> KiB(1).unit_singular == 'KiB' >>> Byte(1024).unit == 'B' >>> Gb(1).unit_singular == 'Gb' """ return self._name_singular #: The "prefix" value of an instance value = property(lambda s: s.prefix_value) @classmethod def from_other(cls, item): """Factory function to return instances of `item` converted into a new instance of ``cls``. Because this is a class method, it may be called from any bitmath class object without the need to explicitly instantiate the class ahead of time. *Implicit Parameter:* * ``cls`` A bitmath class, implicitly set to the class of the instance object it is called on *User Supplied Parameter:* * ``item`` A :class:`bitmath.Bitmath` subclass instance *Example:* >>> import bitmath >>> kib = bitmath.KiB.from_other(bitmath.MiB(1)) >>> print kib KiB(1024.0) """ if isinstance(item, Bitmath): return cls(bits=item.bits) else: raise ValueError("The provided items must be a valid bitmath class: %s" % str(item.__class__)) ###################################################################### # The following implement the Python datamodel customization methods # # Reference: http://docs.python.org/2.7/reference/datamodel.html#basic-customization def __repr__(self): """Representation of this object as you would expect to see in an interpreter""" global _FORMAT_REPR return self.format(_FORMAT_REPR) def __str__(self): """String representation of this object""" global format_string return self.format(format_string) 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) ################################################################## # Guess the best human-readable prefix unit for representation ################################################################## 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() ################################################################## def to_Bit(self): return Bit(self._bit_value) def to_Byte(self): return Byte(self._byte_value / float(NIST_STEPS['Byte'])) # Properties Bit = property(lambda s: s.to_Bit()) Byte = property(lambda s: s.to_Byte()) ################################################################## def to_KiB(self): return KiB(bits=self._bit_value) def to_Kib(self): return Kib(bits=self._bit_value) def to_kB(self): return kB(bits=self._bit_value) def to_kb(self): return kb(bits=self._bit_value) # Properties KiB = property(lambda s: s.to_KiB()) Kib = property(lambda s: s.to_Kib()) kB = property(lambda s: s.to_kB()) kb = property(lambda s: s.to_kb()) ################################################################## def to_MiB(self): return MiB(bits=self._bit_value) def to_Mib(self): return Mib(bits=self._bit_value) def to_MB(self): return MB(bits=self._bit_value) def to_Mb(self): return Mb(bits=self._bit_value) # Properties MiB = property(lambda s: s.to_MiB()) Mib = property(lambda s: s.to_Mib()) MB = property(lambda s: s.to_MB()) Mb = property(lambda s: s.to_Mb()) ################################################################## def to_GiB(self): return GiB(bits=self._bit_value) def to_Gib(self): return Gib(bits=self._bit_value) def to_GB(self): return GB(bits=self._bit_value) def to_Gb(self): return Gb(bits=self._bit_value) # Properties GiB = property(lambda s: s.to_GiB()) Gib = property(lambda s: s.to_Gib()) GB = property(lambda s: s.to_GB()) Gb = property(lambda s: s.to_Gb()) ################################################################## def to_TiB(self): return TiB(bits=self._bit_value) def to_Tib(self): return Tib(bits=self._bit_value) def to_TB(self): return TB(bits=self._bit_value) def to_Tb(self): return Tb(bits=self._bit_value) # Properties TiB = property(lambda s: s.to_TiB()) Tib = property(lambda s: s.to_Tib()) TB = property(lambda s: s.to_TB()) Tb = property(lambda s: s.to_Tb()) ################################################################## def to_PiB(self): return PiB(bits=self._bit_value) def to_Pib(self): return Pib(bits=self._bit_value) def to_PB(self): return PB(bits=self._bit_value) def to_Pb(self): return Pb(bits=self._bit_value) # Properties PiB = property(lambda s: s.to_PiB()) Pib = property(lambda s: s.to_Pib()) PB = property(lambda s: s.to_PB()) Pb = property(lambda s: s.to_Pb()) ################################################################## def to_EiB(self): return EiB(bits=self._bit_value) def to_Eib(self): return Eib(bits=self._bit_value) def to_EB(self): return EB(bits=self._bit_value) def to_Eb(self): return Eb(bits=self._bit_value) # Properties EiB = property(lambda s: s.to_EiB()) Eib = property(lambda s: s.to_Eib()) EB = property(lambda s: s.to_EB()) Eb = property(lambda s: s.to_Eb()) ################################################################## # The SI units go beyond the NIST units. They also have the Zetta # and Yotta prefixes. def to_ZB(self): return ZB(bits=self._bit_value) def to_Zb(self): return Zb(bits=self._bit_value) # Properties ZB = property(lambda s: s.to_ZB()) Zb = property(lambda s: s.to_Zb()) ################################################################## def to_YB(self): return YB(bits=self._bit_value) def to_Yb(self): return Yb(bits=self._bit_value) #: A new object representing this instance as a Yottabyte YB = property(lambda s: s.to_YB()) Yb = property(lambda s: s.to_Yb()) ################################################################## # Rich comparison operations ################################################################## def __lt__(self, other): if isinstance(other, numbers.Number): return self.prefix_value < other else: return self._byte_value < other.bytes def __le__(self, other): if isinstance(other, numbers.Number): return self.prefix_value <= other else: return self._byte_value <= other.bytes def __eq__(self, other): if isinstance(other, numbers.Number): return self.prefix_value == other else: return self._byte_value == other.bytes def __ne__(self, other): if isinstance(other, numbers.Number): return self.prefix_value != other else: return self._byte_value != other.bytes def __gt__(self, other): if isinstance(other, numbers.Number): return self.prefix_value > other else: return self._byte_value > other.bytes def __ge__(self, other): if isinstance(other, numbers.Number): return self.prefix_value >= other else: return self._byte_value >= other.bytes ################################################################## # Basic math operations ################################################################## # Reference: http://docs.python.org/2.7/reference/datamodel.html#emulating-numeric-types """These methods are called to implement the binary arithmetic operations (+, -, *, //, %, divmod(), pow(), **, <<, >>, &, ^, |). For instance, to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, x.__add__(y) is called. The __divmod__() method should be the equivalent to using __floordiv__() and __mod__(); it should not be related to __truediv__() (described below). Note that __pow__() should be defined to accept an optional third argument if the ternary version of the built-in pow() function is to be supported.object.__complex__(self) """ 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) 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) 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) """The division operator (/) is implemented by these methods. The __truediv__() method is used when __future__.division is in effect, otherwise __div__() is used. If only one of these two methods is defined, the object will not support division in the alternate context; TypeError will be raised instead.""" 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) def __truediv__(self, other): # num / bm return self.__div__(other) # def __floordiv__(self, other): # return NotImplemented # def __mod__(self, other): # return NotImplemented # def __divmod__(self, other): # return NotImplemented # def __pow__(self, other, modulo=None): # return NotImplemented ################################################################## """These methods are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. [2] For instance, to evaluate the expression x - y, where y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented. These are the add/sub/mul/div methods for syntax where a number type is given for the LTYPE and a bitmath object is given for the RTYPE. E.g., 3 * MiB(3), or 10 / GB(42) """ def __radd__(self, other): # num + bm = num return other + self.value def __rsub__(self, other): # num - bm = num return other - self.value def __rmul__(self, other): # num * bm = bm return self * other def __rdiv__(self, other): # num / bm = num return other / float(self.value) def __rtruediv__(self, other): # num / bm = num return other / float(self.value) """Called to implement the built-in functions complex(), int(), long(), and float(). Should return a value of the appropriate type. If one of those methods does not support the operation with the supplied arguments, it should return NotImplemented. For bitmath purposes, these methods return the int/long/float equivalent of the this instances prefix Unix value. That is to say: - int(KiB(3.336)) would return 3 - long(KiB(3.336)) would return 3L - float(KiB(3.336)) would return 3.336 """ def __int__(self): """Return this instances prefix unit as an integer""" return int(self.prefix_value) def __long__(self): """Return this instances prefix unit as a long integer""" return long(self.prefix_value) # pragma: PY3X no cover def __float__(self): """Return this instances prefix unit as a floating point number""" return float(self.prefix_value) ################################################################## # Bitwise operations ################################################################## 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) 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) 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) 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) 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) ################################################################## def __neg__(self): """The negative version of this instance""" return (type(self))(-abs(self.prefix_value)) def __pos__(self): return (type(self))(abs(self.prefix_value)) def __abs__(self): return (type(self))(abs(self.prefix_value)) # def __invert__(self): # """Called to implement the unary arithmetic operations (-, +, abs() # and ~).""" # return NotImplemented
(value=0, bytes=None, bits=None)
494
bitmath
_norm
Normalize the input value into the fundamental unit for this prefix type. :param number value: The input value to be normalized :raises ValueError: if the input value is not a type of real number
def _norm(self, value): """Normalize the input value into the fundamental unit for this prefix type. :param number value: The input value to be normalized :raises ValueError: if the input value is not a type of real number """ if isinstance(value, self.valid_types): self._byte_value = value * self._unit_value self._bit_value = self._byte_value * 8.0 else: raise ValueError("Initialization value '%s' is of an invalid type: %s. " "Must be one of %s" % ( value, type(value), ", ".join(str(x) for x in self.valid_types)))
(self, value)
495
bitmath
_set_prefix_value
null
def _set_prefix_value(self): self.prefix_value = self._to_prefix_value(self._byte_value)
(self)
496
bitmath
_setup
null
def _setup(self): raise NotImplementedError("The base 'bitmath.Bitmath' class can not be used directly")
(self)
530
bitmath
Byte
Byte based types fundamentally operate on self._bit_value
class Byte(Bitmath): """Byte based types fundamentally operate on self._bit_value""" def _setup(self): return (2, 0, 'Byte', 'Bytes')
(value=0, bytes=None, bits=None)
564
bitmath
_setup
null
def _setup(self): return (2, 0, 'Byte', 'Bytes')
(self)
598
bitmath
EB
null
class EB(Byte): def _setup(self): return (10, 18, 'EB', 'EBs')
(value=0, bytes=None, bits=None)
632
bitmath
_setup
null
def _setup(self): return (10, 18, 'EB', 'EBs')
(self)
666
bitmath
Eb
null
class Eb(Bit): def _setup(self): return (10, 18, 'Eb', 'Ebs')
(value=0, bytes=None, bits=None)
700
bitmath
_setup
null
def _setup(self): return (10, 18, 'Eb', 'Ebs')
(self)
734
bitmath
EiB
null
class EiB(Byte): def _setup(self): return (2, 60, 'EiB', 'EiBs')
(value=0, bytes=None, bits=None)
768
bitmath
_setup
null
def _setup(self): return (2, 60, 'EiB', 'EiBs')
(self)
802
bitmath
Eib
null
class Eib(Bit): def _setup(self): return (2, 60, 'Eib', 'Eibs')
(value=0, bytes=None, bits=None)
836
bitmath
_setup
null
def _setup(self): return (2, 60, 'Eib', 'Eibs')
(self)
1,006
bitmath
GB
null
class GB(Byte): def _setup(self): return (10, 9, 'GB', 'GBs')
(value=0, bytes=None, bits=None)
1,040
bitmath
_setup
null
def _setup(self): return (10, 9, 'GB', 'GBs')
(self)
1,074
bitmath
Gb
null
class Gb(Bit): def _setup(self): return (10, 9, 'Gb', 'Gbs')
(value=0, bytes=None, bits=None)
1,108
bitmath
_setup
null
def _setup(self): return (10, 9, 'Gb', 'Gbs')
(self)
1,142
bitmath
GiB
null
class GiB(Byte): def _setup(self): return (2, 30, 'GiB', 'GiBs')
(value=0, bytes=None, bits=None)
1,176
bitmath
_setup
null
def _setup(self): return (2, 30, 'GiB', 'GiBs')
(self)
1,210
bitmath
Gib
null
class Gib(Bit): def _setup(self): return (2, 30, 'Gib', 'Gibs')
(value=0, bytes=None, bits=None)
1,244
bitmath
_setup
null
def _setup(self): return (2, 30, 'Gib', 'Gibs')
(self)
1,414
bitmath
KiB
null
class KiB(Byte): def _setup(self): return (2, 10, 'KiB', 'KiBs')
(value=0, bytes=None, bits=None)
1,448
bitmath
_setup
null
def _setup(self): return (2, 10, 'KiB', 'KiBs')
(self)
1,482
bitmath
Kib
null
class Kib(Bit): def _setup(self): return (2, 10, 'Kib', 'Kibs')
(value=0, bytes=None, bits=None)
1,516
bitmath
_setup
null
def _setup(self): return (2, 10, 'Kib', 'Kibs')
(self)
1,618
bitmath
MB
null
class MB(Byte): def _setup(self): return (10, 6, 'MB', 'MBs')
(value=0, bytes=None, bits=None)
1,652
bitmath
_setup
null
def _setup(self): return (10, 6, 'MB', 'MBs')
(self)
1,686
bitmath
Mb
null
class Mb(Bit): def _setup(self): return (10, 6, 'Mb', 'Mbs')
(value=0, bytes=None, bits=None)
1,720
bitmath
_setup
null
def _setup(self): return (10, 6, 'Mb', 'Mbs')
(self)
1,754
bitmath
MiB
null
class MiB(Byte): def _setup(self): return (2, 20, 'MiB', 'MiBs')
(value=0, bytes=None, bits=None)
1,788
bitmath
_setup
null
def _setup(self): return (2, 20, 'MiB', 'MiBs')
(self)
1,822
bitmath
Mib
null
class Mib(Bit): def _setup(self): return (2, 20, 'Mib', 'Mibs')
(value=0, bytes=None, bits=None)
1,856
bitmath
_setup
null
def _setup(self): return (2, 20, 'Mib', 'Mibs')
(self)
2,026
bitmath
PB
null
class PB(Byte): def _setup(self): return (10, 15, 'PB', 'PBs')
(value=0, bytes=None, bits=None)
2,060
bitmath
_setup
null
def _setup(self): return (10, 15, 'PB', 'PBs')
(self)
2,094
bitmath
Pb
null
class Pb(Bit): def _setup(self): return (10, 15, 'Pb', 'Pbs')
(value=0, bytes=None, bits=None)
2,128
bitmath
_setup
null
def _setup(self): return (10, 15, 'Pb', 'Pbs')
(self)
2,162
bitmath
PiB
null
class PiB(Byte): def _setup(self): return (2, 50, 'PiB', 'PiBs')
(value=0, bytes=None, bits=None)
2,196
bitmath
_setup
null
def _setup(self): return (2, 50, 'PiB', 'PiBs')
(self)
2,230
bitmath
Pib
null
class Pib(Bit): def _setup(self): return (2, 50, 'Pib', 'Pibs')
(value=0, bytes=None, bits=None)
2,264
bitmath
_setup
null
def _setup(self): return (2, 50, 'Pib', 'Pibs')
(self)
2,434
bitmath
TB
null
class TB(Byte): def _setup(self): return (10, 12, 'TB', 'TBs')
(value=0, bytes=None, bits=None)
2,468
bitmath
_setup
null
def _setup(self): return (10, 12, 'TB', 'TBs')
(self)
2,502
bitmath
Tb
null
class Tb(Bit): def _setup(self): return (10, 12, 'Tb', 'Tbs')
(value=0, bytes=None, bits=None)
2,536
bitmath
_setup
null
def _setup(self): return (10, 12, 'Tb', 'Tbs')
(self)
2,570
bitmath
TiB
null
class TiB(Byte): def _setup(self): return (2, 40, 'TiB', 'TiBs')
(value=0, bytes=None, bits=None)
2,604
bitmath
_setup
null
def _setup(self): return (2, 40, 'TiB', 'TiBs')
(self)
2,638
bitmath
Tib
null
class Tib(Bit): def _setup(self): return (2, 40, 'Tib', 'Tibs')
(value=0, bytes=None, bits=None)
2,672
bitmath
_setup
null
def _setup(self): return (2, 40, 'Tib', 'Tibs')
(self)
2,842
bitmath
YB
null
class YB(Byte): def _setup(self): return (10, 24, 'YB', 'YBs')
(value=0, bytes=None, bits=None)
2,876
bitmath
_setup
null
def _setup(self): return (10, 24, 'YB', 'YBs')
(self)
2,910
bitmath
Yb
null
class Yb(Bit): def _setup(self): return (10, 24, 'Yb', 'Ybs')
(value=0, bytes=None, bits=None)
2,944
bitmath
_setup
null
def _setup(self): return (10, 24, 'Yb', 'Ybs')
(self)
3,046
bitmath
ZB
null
class ZB(Byte): def _setup(self): return (10, 21, 'ZB', 'ZBs')
(value=0, bytes=None, bits=None)
3,080
bitmath
_setup
null
def _setup(self): return (10, 21, 'ZB', 'ZBs')
(self)
3,114
bitmath
Zb
null
class Zb(Bit): def _setup(self): return (10, 21, 'Zb', 'Zbs')
(value=0, bytes=None, bits=None)
3,148
bitmath
_setup
null
def _setup(self): return (10, 21, 'Zb', 'Zbs')
(self)
3,251
bitmath
best_prefix
Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` keyword. Choices for ``system`` are ``bitmath.NIST`` (default) and ``bitmath.SI``. Basically a shortcut for: >>> import bitmath >>> b = bitmath.Byte(12345) >>> best = b.best_prefix() Or: >>> import bitmath >>> best = (bitmath.KiB(12345) * 4201).best_prefix()
def best_prefix(bytes, system=NIST): """Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` keyword. Choices for ``system`` are ``bitmath.NIST`` (default) and ``bitmath.SI``. Basically a shortcut for: >>> import bitmath >>> b = bitmath.Byte(12345) >>> best = b.best_prefix() Or: >>> import bitmath >>> best = (bitmath.KiB(12345) * 4201).best_prefix() """ if isinstance(bytes, Bitmath): value = bytes.bytes else: value = bytes return Byte(value).best_prefix(system=system)
(bytes, system=2)
3,252
bitmath
capitalize_first
Capitalize ONLY the first letter of the input `s` * returns a copy of input `s` with the first letter capitalized
def capitalize_first(s): """Capitalize ONLY the first letter of the input `s` * returns a copy of input `s` with the first letter capitalized """ pfx = s[0].upper() _s = s[1:] return pfx + _s
(s)
3,253
bitmath
cli_script
null
def cli_script(): # pragma: no cover # Wrapper around cli_script_main so we can unittest the command # line functionality for result in cli_script_main(sys.argv[1:]): print(result)
()
3,254
bitmath
cli_script_main
A command line interface to basic bitmath operations.
def cli_script_main(cli_args): """ A command line interface to basic bitmath operations. """ choices = ALL_UNIT_TYPES parser = argparse.ArgumentParser( description='Converts from one type of size to another.') parser.add_argument('--from-stdin', default=False, action='store_true', help='Reads number from stdin rather than the cli') parser.add_argument( '-f', '--from', choices=choices, nargs=1, type=str, dest='fromunit', default=['Byte'], help='Input type you are converting from. Defaultes to Byte.') parser.add_argument( '-t', '--to', choices=choices, required=False, nargs=1, type=str, help=('Input type you are converting to. ' 'Attempts to detect best result if omitted.'), dest='tounit') parser.add_argument( 'size', nargs='*', type=float, help='The number to convert.') args = parser.parse_args(cli_args) # Not sure how to cover this with tests, or if the functionality # will remain in this form long enough for it to make writing a # test worth the effort. if args.from_stdin: # pragma: no cover args.size = [float(sys.stdin.readline()[:-1])] results = [] for size in args.size: instance = getattr(__import__( 'bitmath', fromlist=['True']), args.fromunit[0])(size) # If we have a unit provided then use it if args.tounit: result = getattr(instance, args.tounit[0]) # Otherwise use the best_prefix call else: result = instance.best_prefix() results.append(result) return results
(cli_args)
3,258
bitmath
format
Context manager for printing bitmath instances. ``fmt_str`` - a formatting mini-language compat formatting string. See the @properties (above) for a list of available items. ``plural`` - True enables printing instances with 's's if they're plural. False (default) prints them as singular (no trailing 's'). ``bestprefix`` - True enables printing instances in their best human-readable representation. False, the default, prints instances using their current prefix unit.
binary = property(lambda s: bin(int(s.bits)))
(fmt_str=None, plural=False, bestprefix=False)
3,259
bitmath
getsize
Return a bitmath instance in the best human-readable representation of the file size at `path`. Optionally, provide a preferred unit system by setting `system` to either `bitmath.NIST` (default) or `bitmath.SI`. Optionally, set ``bestprefix`` to ``False`` to get ``bitmath.Byte`` instances back.
def getsize(path, bestprefix=True, system=NIST): """Return a bitmath instance in the best human-readable representation of the file size at `path`. Optionally, provide a preferred unit system by setting `system` to either `bitmath.NIST` (default) or `bitmath.SI`. Optionally, set ``bestprefix`` to ``False`` to get ``bitmath.Byte`` instances back. """ _path = os.path.realpath(path) size_bytes = os.path.getsize(_path) if bestprefix: return Byte(size_bytes).best_prefix(system=system) else: return Byte(size_bytes)
(path, bestprefix=True, system=2)
3,260
bitmath
kB
null
class kB(Byte): def _setup(self): return (10, 3, 'kB', 'kBs')
(value=0, bytes=None, bits=None)
3,294
bitmath
_setup
null
def _setup(self): return (10, 3, 'kB', 'kBs')
(self)
3,328
bitmath
kb
null
class kb(Bit): def _setup(self): return (10, 3, 'kb', 'kbs')
(value=0, bytes=None, bits=None)
3,362
bitmath
_setup
null
def _setup(self): return (10, 3, 'kb', 'kbs')
(self)
3,464
bitmath
listdir
This is a generator which recurses the directory tree `search_base`, yielding 2-tuples of: * The absolute/relative path to a discovered file * A bitmath instance representing the "apparent size" of the file. - `search_base` - The directory to begin walking down. - `followlinks` - Whether or not to follow symbolic links to directories - `filter` - A glob (see :py:mod:`fnmatch`) to filter results with (default: ``*``, everything) - `relpath` - ``True`` to return the relative path from `pwd` or ``False`` (default) to return the fully qualified path - ``bestprefix`` - set to ``False`` to get ``bitmath.Byte`` instances back instead. - `system` - Provide a preferred unit system by setting `system` to either ``bitmath.NIST`` (default) or ``bitmath.SI``. .. note:: This function does NOT return tuples for directory entities. .. note:: Symlinks to **files** are followed automatically
def listdir(search_base, followlinks=False, filter='*', relpath=False, bestprefix=False, system=NIST): """This is a generator which recurses the directory tree `search_base`, yielding 2-tuples of: * The absolute/relative path to a discovered file * A bitmath instance representing the "apparent size" of the file. - `search_base` - The directory to begin walking down. - `followlinks` - Whether or not to follow symbolic links to directories - `filter` - A glob (see :py:mod:`fnmatch`) to filter results with (default: ``*``, everything) - `relpath` - ``True`` to return the relative path from `pwd` or ``False`` (default) to return the fully qualified path - ``bestprefix`` - set to ``False`` to get ``bitmath.Byte`` instances back instead. - `system` - Provide a preferred unit system by setting `system` to either ``bitmath.NIST`` (default) or ``bitmath.SI``. .. note:: This function does NOT return tuples for directory entities. .. note:: Symlinks to **files** are followed automatically """ for root, dirs, files in os.walk(search_base, followlinks=followlinks): for name in fnmatch.filter(files, filter): _path = os.path.join(root, name) if relpath: # RELATIVE path _return_path = os.path.relpath(_path, '.') else: # REAL path _return_path = os.path.realpath(_path) if followlinks: yield (_return_path, getsize(_path, bestprefix=bestprefix, system=system)) else: if os.path.isdir(_path) or os.path.islink(_path): pass else: yield (_return_path, getsize(_path, bestprefix=bestprefix, system=system))
(search_base, followlinks=False, filter='*', relpath=False, bestprefix=False, system=2)
3,465
builtins
int
int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4
from builtins import int
null
3,469
bitmath
os_name
null
def os_name(): # makes unittesting platform specific code easier return os.name
()
3,470
bitmath
parse_string
Parse a string with units and try to make a bitmath object out of it. String inputs may include whitespace characters between the value and the unit.
def parse_string(s): """Parse a string with units and try to make a bitmath object out of it. String inputs may include whitespace characters between the value and the unit. """ # Strings only please if not isinstance(s, (str, unicode)): raise ValueError("parse_string only accepts string inputs but a %s was given" % type(s)) # get the index of the first alphabetic character try: index = list([i.isalpha() for i in s]).index(True) except ValueError: # If there's no alphabetic characters we won't be able to .index(True) raise ValueError("No unit detected, can not parse string '%s' into a bitmath object" % s) # split the string into the value and the unit val, unit = s[:index], s[index:] # see if the unit exists as a type in our namespace if unit == "b": unit_class = Bit elif unit == "B": unit_class = Byte else: if not (hasattr(sys.modules[__name__], unit) and isinstance(getattr(sys.modules[__name__], unit), type)): raise ValueError("The unit %s is not a valid bitmath unit" % unit) unit_class = globals()[unit] try: val = float(val) except ValueError: raise try: return unit_class(val) except: # pragma: no cover raise ValueError("Can't parse string %s into a bitmath object" % s)
(s)
3,471
bitmath
parse_string_unsafe
Attempt to parse a string with ambiguous units and try to make a bitmath object out of it. This may produce inaccurate results if parsing shell output. For example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB ~= 2.666 KiB. See the documentation for all of the important details. Note the following caveats: * All inputs are assumed to be byte-based (as opposed to bit based) * Numerical inputs (those without any units) are assumed to be a number of bytes * Inputs with single letter units (k, M, G, etc) are assumed to be SI units (base-10). Set the `system` parameter to `bitmath.NIST` to change this behavior. * Inputs with an `i` character following the leading letter (Ki, Mi, Gi) are assumed to be NIST units (base 2) * Capitalization does not matter
def parse_string_unsafe(s, system=SI): """Attempt to parse a string with ambiguous units and try to make a bitmath object out of it. This may produce inaccurate results if parsing shell output. For example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB ~= 2.666 KiB. See the documentation for all of the important details. Note the following caveats: * All inputs are assumed to be byte-based (as opposed to bit based) * Numerical inputs (those without any units) are assumed to be a number of bytes * Inputs with single letter units (k, M, G, etc) are assumed to be SI units (base-10). Set the `system` parameter to `bitmath.NIST` to change this behavior. * Inputs with an `i` character following the leading letter (Ki, Mi, Gi) are assumed to be NIST units (base 2) * Capitalization does not matter """ if not isinstance(s, (str, unicode)) and \ not isinstance(s, numbers.Number): raise ValueError("parse_string_unsafe only accepts string/number inputs but a %s was given" % type(s)) ###################################################################### # Is the input simple to parse? Just a number, or a number # masquerading as a string perhaps? # Test case: raw number input (easy!) if isinstance(s, numbers.Number): # It's just a number. Assume bytes return Byte(s) # Test case: a number pretending to be a string if isinstance(s, (str, unicode)): try: # Can we turn it directly into a number? return Byte(float(s)) except ValueError: # Nope, this is not a plain number pass ###################################################################### # At this point: # - the input is also not just a number wrapped in a string # - nor is is just a plain number type # # We need to do some more digging around now to figure out exactly # what we were given and possibly normalize the input into a # format we can recognize. # First we'll separate the number and the unit. # # Get the index of the first alphabetic character try: index = list([i.isalpha() for i in s]).index(True) except ValueError: # pragma: no cover # If there's no alphabetic characters we won't be able to .index(True) raise ValueError("No unit detected, can not parse string '%s' into a bitmath object" % s) # Split the string into the value and the unit val, unit = s[:index], s[index:] # Don't trust anything. We'll make sure the correct 'b' is in place. unit = unit.rstrip('Bb') unit += 'B' # At this point we can expect `unit` to be either: # # - 2 Characters (for SI, ex: kB or GB) # - 3 Caracters (so NIST, ex: KiB, or GiB) # # A unit with any other number of chars is not a valid unit # SI if len(unit) == 2: # Has NIST parsing been requested? if system == NIST: # NIST units requested. Ensure the unit begins with a # capital letter and is followed by an 'i' character. unit = capitalize_first(unit) # Insert an 'i' char after the first letter _unit = list(unit) _unit.insert(1, 'i') # Collapse the list back into a 3 letter string unit = ''.join(_unit) unit_class = globals()[unit] else: # Default parsing (SI format) # # Edge-case checking: SI 'thousand' is a lower-case K if unit.startswith('K'): unit = unit.replace('K', 'k') elif not unit.startswith('k'): # Otherwise, ensure the first char is capitalized unit = capitalize_first(unit) # This is an SI-type unit if unit[0] in SI_PREFIXES: unit_class = globals()[unit] # NIST elif len(unit) == 3: unit = capitalize_first(unit) # This is a NIST-type unit if unit[:2] in NIST_PREFIXES: unit_class = globals()[unit] else: # This is not a unit we recognize raise ValueError("The unit %s is not a valid bitmath unit" % unit) try: unit_class except UnboundLocalError: raise ValueError("The unit %s is not a valid bitmath unit" % unit) return unit_class(float(val))
(s, system=10)
3,473
bitmath
query_device_capacity
Create bitmath instances of the capacity of a system block device Make one or more ioctl request to query the capacity of a block device. Perform any processing required to compute the final capacity value. Return the device capacity in bytes as a :class:`bitmath.Byte` instance. Thanks to the following resources for help figuring this out Linux/Mac ioctl's for querying block device sizes: * http://stackoverflow.com/a/12925285/263969 * http://stackoverflow.com/a/9764508/263969 :param file device_fd: A ``file`` object of the device to query the capacity of (as in ``get_device_capacity(open("/dev/sda"))``). :return: a bitmath :class:`bitmath.Byte` instance equivalent to the capacity of the target device in bytes.
def query_device_capacity(device_fd): """Create bitmath instances of the capacity of a system block device Make one or more ioctl request to query the capacity of a block device. Perform any processing required to compute the final capacity value. Return the device capacity in bytes as a :class:`bitmath.Byte` instance. Thanks to the following resources for help figuring this out Linux/Mac ioctl's for querying block device sizes: * http://stackoverflow.com/a/12925285/263969 * http://stackoverflow.com/a/9764508/263969 :param file device_fd: A ``file`` object of the device to query the capacity of (as in ``get_device_capacity(open("/dev/sda"))``). :return: a bitmath :class:`bitmath.Byte` instance equivalent to the capacity of the target device in bytes. """ if os_name() != 'posix': raise NotImplementedError("'bitmath.query_device_capacity' is not supported on this platform: %s" % os_name()) s = os.stat(device_fd.name).st_mode if not stat.S_ISBLK(s): raise ValueError("The file descriptor provided is not of a device type") # The keys of the ``ioctl_map`` dictionary correlate to possible # values from the ``platform.system`` function. ioctl_map = { # ioctls for the "Linux" platform "Linux": { "request_params": [ # A list of parameters to calculate the block size. # # ( PARAM_NAME , FORMAT_CHAR , REQUEST_CODE ) ("BLKGETSIZE64", "L", 0x80081272) # Per <linux/fs.h>, the BLKGETSIZE64 request returns a # 'u64' sized value. This is an unsigned 64 bit # integer C type. This means to correctly "buffer" the # result we need 64 bits, or 8 bytes, of memory. # # The struct module documentation include a reference # chart relating formatting characters to native C # Types. In this case, using the "native size", the # table tells us: # # * Character 'L' - Unsigned Long C Type (u64) - Loads into a Python int type # # Confirm this character is right by running (on Linux): # # >>> import struct # >>> print 8 == struct.calcsize('L') # # The result should be true as long as your kernel # headers define BLKGETSIZE64 as a u64 type (please # file a bug report at # https://github.com/tbielawa/bitmath/issues/new if # this does *not* work for you) ], # func is how the final result is decided. Because the # Linux BLKGETSIZE64 call returns the block device # capacity in bytes as an integer value, no extra # calculations are required. Simply return the value of # BLKGETSIZE64. "func": lambda x: x["BLKGETSIZE64"] }, # ioctls for the "Darwin" (Mac OS X) platform "Darwin": { "request_params": [ # A list of parameters to calculate the block size. # # ( PARAM_NAME , FORMAT_CHAR , REQUEST_CODE ) ("DKIOCGETBLOCKCOUNT", "L", 0x40086419), # Per <sys/disk.h>: get media's block count - uint64_t # # As in the BLKGETSIZE64 example, an unsigned 64 bit # integer will use the 'L' formatting character ("DKIOCGETBLOCKSIZE", "I", 0x40046418) # Per <sys/disk.h>: get media's block size - uint32_t # # This request returns an unsigned 32 bit integer, or # in other words: just a normal integer (or 'int' c # type). That should require 4 bytes of space for # buffering. According to the struct modules # 'Formatting Characters' chart: # # * Character 'I' - Unsigned Int C Type (uint32_t) - Loads into a Python int type ], # OS X doesn't have a direct equivalent to the Linux # BLKGETSIZE64 request. Instead, we must request how many # blocks (or "sectors") are on the disk, and the size (in # bytes) of each block. Finally, multiply the two together # to obtain capacity: # # n Block * y Byte # capacity (bytes) = ------- # 1 Block "func": lambda x: x["DKIOCGETBLOCKCOUNT"] * x["DKIOCGETBLOCKSIZE"] # This expression simply accepts a dictionary ``x`` as a # parameter, and then returns the result of multiplying # the two named dictionary items together. In this case, # that means multiplying ``DKIOCGETBLOCKCOUNT``, the total # number of blocks, by ``DKIOCGETBLOCKSIZE``, the size of # each block in bytes. } } platform_params = ioctl_map[platform.system()] results = {} for req_name, fmt, request_code in platform_params['request_params']: # Read the systems native size (in bytes) of this format type. buffer_size = struct.calcsize(fmt) # Construct a buffer to store the ioctl result in buffer = ' ' * buffer_size # This code has been ran on only a few test systems. If it's # appropriate, maybe in the future we'll add try/except # conditions for some possible errors. Really only for cases # where it would add value to override the default exception # message string. buffer = fcntl.ioctl(device_fd.fileno(), request_code, buffer) # Unpack the raw result from the ioctl call into a familiar # python data type according to the ``fmt`` rules. result = struct.unpack(fmt, buffer)[0] # Add the new result to our collection results[req_name] = result return Byte(platform_params['func'](results))
(device_fd)
3,478
xml_python
Builder
A builder for returning python objects from xml ``Element`` instances. Given a single node and a input object, a builder can transform the input object according to the data found in the provided element. To parse a tag, use the :meth:`~Builder.parse_element` method. :ivar ~Builder.maker: The method which will make an initial object for this builder to work on. :ivar ~Builder.name: A name to differentiate a builder when debugging. :ivar ~Builder>parsers: A dictionary of parser functions mapped to tag names. :ivar ~Builder.builders: A dictionary a sub builders, mapped to tag names.
class Builder(Generic[InputObjectType, OutputObjectType]): """A builder for returning python objects from xml ``Element`` instances. Given a single node and a input object, a builder can transform the input object according to the data found in the provided element. To parse a tag, use the :meth:`~Builder.parse_element` method. :ivar ~Builder.maker: The method which will make an initial object for this builder to work on. :ivar ~Builder.name: A name to differentiate a builder when debugging. :ivar ~Builder>parsers: A dictionary of parser functions mapped to tag names. :ivar ~Builder.builders: A dictionary a sub builders, mapped to tag names. """ maker: MakerType = attrib(repr=False) name: Optional[str] = None parsers: Dict[str, ParserType] = attrib(default=Factory(dict), repr=False) builders: Dict[str, 'Builder'] = attrib(default=Factory(dict), repr=False) def build( self, input_object: Optional[InputObjectType], element: Element ) -> OutputObjectType: """Make the initial object, then handle the element. If you are looking to build an object from an xml element, this is likely the method you want. :param input_object: An optional input object for the provided elements to work on. :param element: The element to handle. """ output_object: OutputObjectType = self.maker(input_object, element) self.handle_elements(output_object, list(element)) return output_object def handle_elements( self, subject: OutputObjectType, elements: List[Element] ) -> None: """Handle each of the given elements. This method is usually called by the :meth:`~Builder.make_and_handle` method. :param subject: The object to maniplate with the given elements. :param elements: The elements to work through. """ element: Element for element in elements: tag: str = element.tag if tag in self.parsers: self.parsers[tag](subject, element) elif tag in self.builders: builder: Builder[OutputObjectType, Any] = self.builders[tag] obj: Any = builder.maker(subject, element, ) builder.handle_elements(obj, list(element)) else: raise UnhandledElement(self, element) def handle_string(self, xml: str) -> OutputObjectType: """Parse and handle an element from a string. :param xml: The xml string to parse. """ element: Element = fromstring(xml) return self.build(None, element) def handle_file(self, fileobj: IO[str]) -> OutputObjectType: """Handle a file-like object. :param fileobj: The file-like object to read XML from. """ return self.handle_string(fileobj.read()) def handle_filename(self, filename: str) -> OutputObjectType: """Return an element made from a file with the given name. :param filename: The name of the file to load. """ root: ElementTree = parse((filename)) e: Element = root.getroot() return self.build(None, e) def parser(self, tag: str) -> Callable[[ParserType], ParserType]: """Add a new parser to this builder. Parsers work on the name on a tag. So if you wish to work on the XML ``<title>Hello, title</title>``, you need a parser that knows how to handle the ``title`` tag. :param tag: The tag name this parser will handle. """ def inner(func: ParserType) -> ParserType: """Add ``func`` to the :attr:`~Builder.parsers` dictionary. :param func: The function to add. """ self.add_parser(tag, func) return func return inner def add_parser(self, tag: str, func: ParserType) -> None: """Add a parser to this builder. :param tag: The name of the tag that this parser knows how to handle. :param func: The function which will do the actual parsing. """ self.parsers[tag] = func def add_builder(self, tag: str, builder: 'Builder') -> None: """Add a sub builder to this builder. In the same way that parsers know how to handle a single tag, sub builders can handle many tags recursively. :param tag: The name of the top level tag this sub builder knows how to handle. :param builder: The builder to add. """ self.builders[tag] = builder
(maker: Callable[[Optional[~InputObjectType], xml.etree.ElementTree.Element], ~OutputObjectType], name: Optional[str] = None, parsers: Dict[str, Callable[[~OutputObjectType, xml.etree.ElementTree.Element], NoneType]] = NOTHING, builders: Dict[str, xml_python.Builder] = NOTHING) -> None
3,479
xml_python
__eq__
Method generated by attrs for class Builder.
"""The xml_python library. A library for converting XML into python objects. Provides the Builder class. """ from typing import IO, Any, Callable, Dict, Generic, List, Optional, TypeVar from xml.etree.ElementTree import Element, ElementTree, fromstring, parse from attr import Factory, attrib, attrs __all__: List[str] = [ 'InputObjectType', 'OutputObjectType', 'TextType', 'AttribType', 'MakerType', 'ParserType', 'NoneType', 'BuilderError', 'UnhandledElement', 'Builder' ] InputObjectType = TypeVar('InputObjectType') OutputObjectType = TypeVar('OutputObjectType') TextType = Optional[str] AttribType = Dict[str, str] MakerType = Callable[[Optional[InputObjectType], Element], OutputObjectType] ParserType = Callable[[OutputObjectType, Element], None] NoneType = type(None) class BuilderError(Exception): """Base exception."""
(self, other)
3,480
xml_python
__ge__
Method generated by attrs for class Builder.
null
(self, other)
3,487
xml_python
add_builder
Add a sub builder to this builder. In the same way that parsers know how to handle a single tag, sub builders can handle many tags recursively. :param tag: The name of the top level tag this sub builder knows how to handle. :param builder: The builder to add.
def add_builder(self, tag: str, builder: 'Builder') -> None: """Add a sub builder to this builder. In the same way that parsers know how to handle a single tag, sub builders can handle many tags recursively. :param tag: The name of the top level tag this sub builder knows how to handle. :param builder: The builder to add. """ self.builders[tag] = builder
(self, tag: str, builder: xml_python.Builder) -> NoneType
3,488
xml_python
add_parser
Add a parser to this builder. :param tag: The name of the tag that this parser knows how to handle. :param func: The function which will do the actual parsing.
def add_parser(self, tag: str, func: ParserType) -> None: """Add a parser to this builder. :param tag: The name of the tag that this parser knows how to handle. :param func: The function which will do the actual parsing. """ self.parsers[tag] = func
(self, tag: str, func: Callable[[~OutputObjectType, xml.etree.ElementTree.Element], NoneType]) -> NoneType
3,489
xml_python
build
Make the initial object, then handle the element. If you are looking to build an object from an xml element, this is likely the method you want. :param input_object: An optional input object for the provided elements to work on. :param element: The element to handle.
def build( self, input_object: Optional[InputObjectType], element: Element ) -> OutputObjectType: """Make the initial object, then handle the element. If you are looking to build an object from an xml element, this is likely the method you want. :param input_object: An optional input object for the provided elements to work on. :param element: The element to handle. """ output_object: OutputObjectType = self.maker(input_object, element) self.handle_elements(output_object, list(element)) return output_object
(self, input_object: Optional[~InputObjectType], element: xml.etree.ElementTree.Element) -> ~OutputObjectType
3,490
xml_python
handle_elements
Handle each of the given elements. This method is usually called by the :meth:`~Builder.make_and_handle` method. :param subject: The object to maniplate with the given elements. :param elements: The elements to work through.
def handle_elements( self, subject: OutputObjectType, elements: List[Element] ) -> None: """Handle each of the given elements. This method is usually called by the :meth:`~Builder.make_and_handle` method. :param subject: The object to maniplate with the given elements. :param elements: The elements to work through. """ element: Element for element in elements: tag: str = element.tag if tag in self.parsers: self.parsers[tag](subject, element) elif tag in self.builders: builder: Builder[OutputObjectType, Any] = self.builders[tag] obj: Any = builder.maker(subject, element, ) builder.handle_elements(obj, list(element)) else: raise UnhandledElement(self, element)
(self, subject: ~OutputObjectType, elements: List[xml.etree.ElementTree.Element]) -> NoneType
3,491
xml_python
handle_file
Handle a file-like object. :param fileobj: The file-like object to read XML from.
def handle_file(self, fileobj: IO[str]) -> OutputObjectType: """Handle a file-like object. :param fileobj: The file-like object to read XML from. """ return self.handle_string(fileobj.read())
(self, fileobj: IO[str]) -> ~OutputObjectType
3,492
xml_python
handle_filename
Return an element made from a file with the given name. :param filename: The name of the file to load.
def handle_filename(self, filename: str) -> OutputObjectType: """Return an element made from a file with the given name. :param filename: The name of the file to load. """ root: ElementTree = parse((filename)) e: Element = root.getroot() return self.build(None, e)
(self, filename: str) -> ~OutputObjectType
3,493
xml_python
handle_string
Parse and handle an element from a string. :param xml: The xml string to parse.
def handle_string(self, xml: str) -> OutputObjectType: """Parse and handle an element from a string. :param xml: The xml string to parse. """ element: Element = fromstring(xml) return self.build(None, element)
(self, xml: str) -> ~OutputObjectType