desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process.'
| def evaluate(self, environment=None):
| current_environment = default_environment()
if (environment is not None):
current_environment.update(environment)
return _evaluate_markers(self._markers, current_environment)
|
'Return the longhand version of the IP address as a string.'
| @property
def exploded(self):
| return self._explode_shorthand_ip_string()
|
'Return the shorthand version of the IP address as a string.'
| @property
def compressed(self):
| return _compat_str(self)
|
'The name of the reverse DNS pointer for the IP address, e.g.:
>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
\'1.0.0.127.in-addr.arpa\'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
\'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\''
| @property
def reverse_pointer(self):
| return self._reverse_pointer()
|
'Turn the prefix length into a bitwise netmask
Args:
prefixlen: An integer, the prefix length.
Returns:
An integer.'
| @classmethod
def _ip_int_from_prefix(cls, prefixlen):
| return (cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen))
|
'Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones'
| @classmethod
def _prefix_from_ip_int(cls, ip_int):
| trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen)
prefixlen = (cls._max_prefixlen - trailing_zeroes)
leading_ones = (ip_int >> trailing_zeroes)
all_ones = ((1 << prefixlen) - 1)
if (leading_ones != all_ones):
byteslen = (cls._max_prefixlen // 8)
details = _compat_to_bytes(ip_int, byteslen, u'big')
msg = u'Netmask pattern %r mixes zeroes & ones'
raise ValueError((msg % details))
return prefixlen
|
'Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask'
| @classmethod
def _prefix_from_prefix_string(cls, prefixlen_str):
| if (not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str)):
cls._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
cls._report_invalid_netmask(prefixlen_str)
if (not (0 <= prefixlen <= cls._max_prefixlen)):
cls._report_invalid_netmask(prefixlen_str)
return prefixlen
|
'Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask'
| @classmethod
def _prefix_from_ip_string(cls, ip_str):
| try:
ip_int = cls._ip_int_from_string(ip_str)
except AddressValueError:
cls._report_invalid_netmask(ip_str)
try:
return cls._prefix_from_ip_int(ip_int)
except ValueError:
pass
ip_int ^= cls._ALL_ONES
try:
return cls._prefix_from_ip_int(ip_int)
except ValueError:
cls._report_invalid_netmask(ip_str)
|
'Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn\'t return the network
or broadcast addresses.'
| def hosts(self):
| network = int(self.network_address)
broadcast = int(self.broadcast_address)
for x in _compat_range((network + 1), broadcast):
(yield self._address_class(x))
|
'Tell if self is partly contained in other.'
| def overlaps(self, other):
| return ((self.network_address in other) or ((self.broadcast_address in other) or ((other.network_address in self) or (other.broadcast_address in self))))
|
'Number of hosts in the current subnet.'
| @property
def num_addresses(self):
| return ((int(self.broadcast_address) - int(self.network_address)) + 1)
|
'Remove an address from a larger block.
For example:
addr1 = ip_network(\'192.0.2.0/28\')
addr2 = ip_network(\'192.0.2.1/32\')
addr1.address_exclude(addr2) =
[IPv4Network(\'192.0.2.0/32\'), IPv4Network(\'192.0.2.2/31\'),
IPv4Network(\'192.0.2.4/30\'), IPv4Network(\'192.0.2.8/29\')]
or IPv6:
addr1 = ip_network(\'2001:db8::1/32\')
addr2 = ip_network(\'2001:db8::1/128\')
addr1.address_exclude(addr2) =
[ip_network(\'2001:db8::1/128\'),
ip_network(\'2001:db8::2/127\'),
ip_network(\'2001:db8::4/126\'),
ip_network(\'2001:db8::8/125\'),
ip_network(\'2001:db8:8000::/33\')]
Args:
other: An IPv4Network or IPv6Network object of the same type.
Returns:
An iterator of the IPv(4|6)Network objects which is self
minus other.
Raises:
TypeError: If self and other are of differing address
versions, or if other is not a network object.
ValueError: If other is not completely contained by self.'
| def address_exclude(self, other):
| if (not (self._version == other._version)):
raise TypeError((u'%s and %s are not of the same version' % (self, other)))
if (not isinstance(other, _BaseNetwork)):
raise TypeError((u'%s is not a network object' % other))
if (not other.subnet_of(self)):
raise ValueError((u'%s not contained in %s' % (other, self)))
if (other == self):
return
other = other.__class__((u'%s/%s' % (other.network_address, other.prefixlen)))
(s1, s2) = self.subnets()
while ((s1 != other) and (s2 != other)):
if other.subnet_of(s1):
(yield s2)
(s1, s2) = s1.subnets()
elif other.subnet_of(s2):
(yield s1)
(s1, s2) = s2.subnets()
else:
raise AssertionError((u'Error performing exclusion: s1: %s s2: %s other: %s' % (s1, s2, other)))
if (s1 == other):
(yield s2)
elif (s2 == other):
(yield s1)
else:
raise AssertionError((u'Error performing exclusion: s1: %s s2: %s other: %s' % (s1, s2, other)))
|
'Compare two IP objects.
This is only concerned about the comparison of the integer
representation of the network addresses. This means that the
host bits aren\'t considered at all in this method. If you want
to compare host bits, you can easily enough do a
\'HostA._ip < HostB._ip\'
Args:
other: An IP object.
Returns:
If the IP versions of self and other are the same, returns:
-1 if self < other:
eg: IPv4Network(\'192.0.2.0/25\') < IPv4Network(\'192.0.2.128/25\')
IPv6Network(\'2001:db8::1000/124\') <
IPv6Network(\'2001:db8::2000/124\')
0 if self == other
eg: IPv4Network(\'192.0.2.0/24\') == IPv4Network(\'192.0.2.0/24\')
IPv6Network(\'2001:db8::1000/124\') ==
IPv6Network(\'2001:db8::1000/124\')
1 if self > other
eg: IPv4Network(\'192.0.2.128/25\') > IPv4Network(\'192.0.2.0/25\')
IPv6Network(\'2001:db8::2000/124\') >
IPv6Network(\'2001:db8::1000/124\')
Raises:
TypeError if the IP versions are different.'
| def compare_networks(self, other):
| if (self._version != other._version):
raise TypeError((u'%s and %s are not of the same type' % (self, other)))
if (self.network_address < other.network_address):
return (-1)
if (self.network_address > other.network_address):
return 1
if (self.netmask < other.netmask):
return (-1)
if (self.netmask > other.netmask):
return 1
return 0
|
'Network-only key function.
Returns an object that identifies this address\' network and
netmask. This function is a suitable "key" argument for sorted()
and list.sort().'
| def _get_networks_key(self):
| return (self._version, self.network_address, self.netmask)
|
'The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network)'
| def subnets(self, prefixlen_diff=1, new_prefix=None):
| if (self._prefixlen == self._max_prefixlen):
(yield self)
return
if (new_prefix is not None):
if (new_prefix < self._prefixlen):
raise ValueError(u'new prefix must be longer')
if (prefixlen_diff != 1):
raise ValueError(u'cannot set prefixlen_diff and new_prefix')
prefixlen_diff = (new_prefix - self._prefixlen)
if (prefixlen_diff < 0):
raise ValueError(u'prefix length diff must be > 0')
new_prefixlen = (self._prefixlen + prefixlen_diff)
if (new_prefixlen > self._max_prefixlen):
raise ValueError((u'prefix length diff %d is invalid for netblock %s' % (new_prefixlen, self)))
start = int(self.network_address)
end = int(self.broadcast_address)
step = ((int(self.hostmask) + 1) >> prefixlen_diff)
for new_addr in _compat_range(start, end, step):
current = self.__class__((new_addr, new_prefixlen))
(yield current)
|
'The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network)'
| def supernet(self, prefixlen_diff=1, new_prefix=None):
| if (self._prefixlen == 0):
return self
if (new_prefix is not None):
if (new_prefix > self._prefixlen):
raise ValueError(u'new prefix must be shorter')
if (prefixlen_diff != 1):
raise ValueError(u'cannot set prefixlen_diff and new_prefix')
prefixlen_diff = (self._prefixlen - new_prefix)
new_prefixlen = (self.prefixlen - prefixlen_diff)
if (new_prefixlen < 0):
raise ValueError((u'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)))
return self.__class__(((int(self.network_address) & (int(self.netmask) << prefixlen_diff)), new_prefixlen))
|
'Test if the address is reserved for multicast use.
Returns:
A boolean, True if the address is a multicast address.
See RFC 2373 2.7 for details.'
| @property
def is_multicast(self):
| return (self.network_address.is_multicast and self.broadcast_address.is_multicast)
|
'Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.'
| @property
def is_reserved(self):
| return (self.network_address.is_reserved and self.broadcast_address.is_reserved)
|
'Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is reserved per RFC 4291.'
| @property
def is_link_local(self):
| return (self.network_address.is_link_local and self.broadcast_address.is_link_local)
|
'Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry or iana-ipv6-special-registry.'
| @property
def is_private(self):
| return (self.network_address.is_private and self.broadcast_address.is_private)
|
'Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry or iana-ipv6-special-registry.'
| @property
def is_global(self):
| return (not self.is_private)
|
'Test if the address is unspecified.
Returns:
A boolean, True if this is the unspecified address as defined in
RFC 2373 2.5.2.'
| @property
def is_unspecified(self):
| return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified)
|
'Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback address as defined in
RFC 2373 2.5.3.'
| @property
def is_loopback(self):
| return (self.network_address.is_loopback and self.broadcast_address.is_loopback)
|
'Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")'
| @classmethod
def _make_netmask(cls, arg):
| if (arg not in cls._netmask_cache):
if isinstance(arg, _compat_int_types):
prefixlen = arg
else:
try:
prefixlen = cls._prefix_from_prefix_string(arg)
except NetmaskValueError:
prefixlen = cls._prefix_from_ip_string(arg)
netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = (netmask, prefixlen)
return cls._netmask_cache[arg]
|
'Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn\'t a valid IPv4 Address.'
| @classmethod
def _ip_int_from_string(cls, ip_str):
| if (not ip_str):
raise AddressValueError(u'Address cannot be empty')
octets = ip_str.split(u'.')
if (len(octets) != 4):
raise AddressValueError((u'Expected 4 octets in %r' % ip_str))
try:
return _compat_int_from_byte_vals(map(cls._parse_octet, octets), u'big')
except ValueError as exc:
raise AddressValueError((u'%s in %r' % (exc, ip_str)))
|
'Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn\'t strictly a decimal from [0..255].'
| @classmethod
def _parse_octet(cls, octet_str):
| if (not octet_str):
raise ValueError(u'Empty octet not permitted')
if (not cls._DECIMAL_DIGITS.issuperset(octet_str)):
msg = u'Only decimal digits permitted in %r'
raise ValueError((msg % octet_str))
if (len(octet_str) > 3):
msg = u'At most 3 characters permitted in %r'
raise ValueError((msg % octet_str))
octet_int = int(octet_str, 10)
if ((octet_int > 7) and (octet_str[0] == u'0')):
msg = u'Ambiguous (octal/decimal) value in %r not permitted'
raise ValueError((msg % octet_str))
if (octet_int > 255):
raise ValueError((u'Octet %d (> 255) not permitted' % octet_int))
return octet_int
|
'Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation.'
| @classmethod
def _string_from_ip_int(cls, ip_int):
| return u'.'.join((_compat_str((struct.unpack('!B', b)[0] if isinstance(b, bytes) else b)) for b in _compat_to_bytes(ip_int, 4, u'big')))
|
'Test if the IP string is a hostmask (rather than a netmask).
Args:
ip_str: A string, the potential hostmask.
Returns:
A boolean, True if the IP string is a hostmask.'
| def _is_hostmask(self, ip_str):
| bits = ip_str.split(u'.')
try:
parts = [x for x in map(int, bits) if (x in self._valid_mask_octets)]
except ValueError:
return False
if (len(parts) != len(bits)):
return False
if (parts[0] < parts[(-1)]):
return True
return False
|
'Return the reverse DNS pointer name for the IPv4 address.
This implements the method described in RFC1035 3.5.'
| def _reverse_pointer(self):
| reverse_octets = _compat_str(self).split(u'.')[::(-1)]
return (u'.'.join(reverse_octets) + u'.in-addr.arpa')
|
'Args:
address: A string or integer representing the IP
Additionally, an integer can be passed, so
IPv4Address(\'192.0.2.1\') == IPv4Address(3221225985).
or, more generally
IPv4Address(int(IPv4Address(\'192.0.2.1\'))) ==
IPv4Address(\'192.0.2.1\')
Raises:
AddressValueError: If ipaddress isn\'t a valid IPv4 address.'
| def __init__(self, address):
| if isinstance(address, _compat_int_types):
self._check_int_address(address)
self._ip = address
return
if isinstance(address, bytes):
self._check_packed_address(address, 4)
bvs = _compat_bytes_to_byte_vals(address)
self._ip = _compat_int_from_byte_vals(bvs, u'big')
return
addr_str = _compat_str(address)
if (u'/' in addr_str):
raise AddressValueError((u"Unexpected '/' in %r" % address))
self._ip = self._ip_int_from_string(addr_str)
|
'The binary representation of this address.'
| @property
def packed(self):
| return v4_int_to_packed(self._ip)
|
'Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within the
reserved IPv4 Network range.'
| @property
def is_reserved(self):
| return (self in self._constants._reserved_network)
|
'Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry.'
| @property
def is_private(self):
| return any(((self in net) for net in self._constants._private_networks))
|
'Test if the address is reserved for multicast use.
Returns:
A boolean, True if the address is multicast.
See RFC 3171 for details.'
| @property
def is_multicast(self):
| return (self in self._constants._multicast_network)
|
'Test if the address is unspecified.
Returns:
A boolean, True if this is the unspecified address as defined in
RFC 5735 3.'
| @property
def is_unspecified(self):
| return (self == self._constants._unspecified_address)
|
'Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback per RFC 3330.'
| @property
def is_loopback(self):
| return (self in self._constants._loopback_network)
|
'Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is link-local per RFC 3927.'
| @property
def is_link_local(self):
| return (self in self._constants._linklocal_network)
|
'Instantiate a new IPv4 network object.
Args:
address: A string or integer representing the IP [& network].
\'192.0.2.0/24\'
\'192.0.2.0/255.255.255.0\'
\'192.0.0.2/0.0.0.255\'
are all functionally the same in IPv4. Similarly,
\'192.0.2.1\'
\'192.0.2.1/255.255.255.255\'
\'192.0.2.1/32\'
are also functionally equivalent. That is to say, failing to
provide a subnetmask will create an object with a mask of /32.
If the mask (portion after the / in the argument) is given in
dotted quad form, it is treated as a netmask if it starts with a
non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
starts with a zero field (e.g. 0.255.255.255 == /8), with the
single exception of an all-zero mask which is treated as a
netmask == /0. If no mask is given, a default of /32 is used.
Additionally, an integer can be passed, so
IPv4Network(\'192.0.2.1\') == IPv4Network(3221225985)
or, more generally
IPv4Interface(int(IPv4Interface(\'192.0.2.1\'))) ==
IPv4Interface(\'192.0.2.1\')
Raises:
AddressValueError: If ipaddress isn\'t a valid IPv4 address.
NetmaskValueError: If the netmask isn\'t valid for
an IPv4 address.
ValueError: If strict is True and a network address is not
supplied.'
| def __init__(self, address, strict=True):
| _BaseNetwork.__init__(self, address)
if isinstance(address, (_compat_int_types, bytes)):
self.network_address = IPv4Address(address)
(self.netmask, self._prefixlen) = self._make_netmask(self._max_prefixlen)
return
if isinstance(address, tuple):
if (len(address) > 1):
arg = address[1]
else:
arg = self._max_prefixlen
self.network_address = IPv4Address(address[0])
(self.netmask, self._prefixlen) = self._make_netmask(arg)
packed = int(self.network_address)
if ((packed & int(self.netmask)) != packed):
if strict:
raise ValueError((u'%s has host bits set' % self))
else:
self.network_address = IPv4Address((packed & int(self.netmask)))
return
addr = _split_optional_netmask(address)
self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
if (len(addr) == 2):
arg = addr[1]
else:
arg = self._max_prefixlen
(self.netmask, self._prefixlen) = self._make_netmask(arg)
if strict:
if (IPv4Address((int(self.network_address) & int(self.netmask))) != self.network_address):
raise ValueError((u'%s has host bits set' % self))
self.network_address = IPv4Address((int(self.network_address) & int(self.netmask)))
if (self._prefixlen == (self._max_prefixlen - 1)):
self.hosts = self.__iter__
|
'Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry.'
| @property
def is_global(self):
| return ((not ((self.network_address in IPv4Network(u'100.64.0.0/10')) and (self.broadcast_address in IPv4Network(u'100.64.0.0/10')))) and (not self.is_private))
|
'Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")'
| @classmethod
def _make_netmask(cls, arg):
| if (arg not in cls._netmask_cache):
if isinstance(arg, _compat_int_types):
prefixlen = arg
else:
prefixlen = cls._prefix_from_prefix_string(arg)
netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = (netmask, prefixlen)
return cls._netmask_cache[arg]
|
'Turn an IPv6 ip_str into an integer.
Args:
ip_str: A string, the IPv6 ip_str.
Returns:
An int, the IPv6 address
Raises:
AddressValueError: if ip_str isn\'t a valid IPv6 Address.'
| @classmethod
def _ip_int_from_string(cls, ip_str):
| if (not ip_str):
raise AddressValueError(u'Address cannot be empty')
parts = ip_str.split(u':')
_min_parts = 3
if (len(parts) < _min_parts):
msg = (u'At least %d parts expected in %r' % (_min_parts, ip_str))
raise AddressValueError(msg)
if (u'.' in parts[(-1)]):
try:
ipv4_int = IPv4Address(parts.pop())._ip
except AddressValueError as exc:
raise AddressValueError((u'%s in %r' % (exc, ip_str)))
parts.append((u'%x' % ((ipv4_int >> 16) & 65535)))
parts.append((u'%x' % (ipv4_int & 65535)))
_max_parts = (cls._HEXTET_COUNT + 1)
if (len(parts) > _max_parts):
msg = (u'At most %d colons permitted in %r' % ((_max_parts - 1), ip_str))
raise AddressValueError(msg)
skip_index = None
for i in _compat_range(1, (len(parts) - 1)):
if (not parts[i]):
if (skip_index is not None):
msg = (u"At most one '::' permitted in %r" % ip_str)
raise AddressValueError(msg)
skip_index = i
if (skip_index is not None):
parts_hi = skip_index
parts_lo = ((len(parts) - skip_index) - 1)
if (not parts[0]):
parts_hi -= 1
if parts_hi:
msg = u"Leading ':' only permitted as part of '::' in %r"
raise AddressValueError((msg % ip_str))
if (not parts[(-1)]):
parts_lo -= 1
if parts_lo:
msg = u"Trailing ':' only permitted as part of '::' in %r"
raise AddressValueError((msg % ip_str))
parts_skipped = (cls._HEXTET_COUNT - (parts_hi + parts_lo))
if (parts_skipped < 1):
msg = u"Expected at most %d other parts with '::' in %r"
raise AddressValueError((msg % ((cls._HEXTET_COUNT - 1), ip_str)))
else:
if (len(parts) != cls._HEXTET_COUNT):
msg = u"Exactly %d parts expected without '::' in %r"
raise AddressValueError((msg % (cls._HEXTET_COUNT, ip_str)))
if (not parts[0]):
msg = u"Leading ':' only permitted as part of '::' in %r"
raise AddressValueError((msg % ip_str))
if (not parts[(-1)]):
msg = u"Trailing ':' only permitted as part of '::' in %r"
raise AddressValueError((msg % ip_str))
parts_hi = len(parts)
parts_lo = 0
parts_skipped = 0
try:
ip_int = 0
for i in range(parts_hi):
ip_int <<= 16
ip_int |= cls._parse_hextet(parts[i])
ip_int <<= (16 * parts_skipped)
for i in range((- parts_lo), 0):
ip_int <<= 16
ip_int |= cls._parse_hextet(parts[i])
return ip_int
except ValueError as exc:
raise AddressValueError((u'%s in %r' % (exc, ip_str)))
|
'Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn\'t strictly a hex number from
[0..FFFF].'
| @classmethod
def _parse_hextet(cls, hextet_str):
| if (not cls._HEX_DIGITS.issuperset(hextet_str)):
raise ValueError((u'Only hex digits permitted in %r' % hextet_str))
if (len(hextet_str) > 4):
msg = u'At most 4 characters permitted in %r'
raise ValueError((msg % hextet_str))
return int(hextet_str, 16)
|
'Compresses a list of hextets.
Compresses a list of strings, replacing the longest continuous
sequence of "0" in the list with "" and adding empty strings at
the beginning or at the end of the string such that subsequently
calling ":".join(hextets) will produce the compressed version of
the IPv6 address.
Args:
hextets: A list of strings, the hextets to compress.
Returns:
A list of strings.'
| @classmethod
def _compress_hextets(cls, hextets):
| best_doublecolon_start = (-1)
best_doublecolon_len = 0
doublecolon_start = (-1)
doublecolon_len = 0
for (index, hextet) in enumerate(hextets):
if (hextet == u'0'):
doublecolon_len += 1
if (doublecolon_start == (-1)):
doublecolon_start = index
if (doublecolon_len > best_doublecolon_len):
best_doublecolon_len = doublecolon_len
best_doublecolon_start = doublecolon_start
else:
doublecolon_len = 0
doublecolon_start = (-1)
if (best_doublecolon_len > 1):
best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len)
if (best_doublecolon_end == len(hextets)):
hextets += [u'']
hextets[best_doublecolon_start:best_doublecolon_end] = [u'']
if (best_doublecolon_start == 0):
hextets = ([u''] + hextets)
return hextets
|
'Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones.'
| @classmethod
def _string_from_ip_int(cls, ip_int=None):
| if (ip_int is None):
ip_int = int(cls._ip)
if (ip_int > cls._ALL_ONES):
raise ValueError(u'IPv6 address is too large')
hex_str = (u'%032x' % ip_int)
hextets = [(u'%x' % int(hex_str[x:(x + 4)], 16)) for x in range(0, 32, 4)]
hextets = cls._compress_hextets(hextets)
return u':'.join(hextets)
|
'Expand a shortened IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A string, the expanded IPv6 address.'
| def _explode_shorthand_ip_string(self):
| if isinstance(self, IPv6Network):
ip_str = _compat_str(self.network_address)
elif isinstance(self, IPv6Interface):
ip_str = _compat_str(self.ip)
else:
ip_str = _compat_str(self)
ip_int = self._ip_int_from_string(ip_str)
hex_str = (u'%032x' % ip_int)
parts = [hex_str[x:(x + 4)] for x in range(0, 32, 4)]
if isinstance(self, (_BaseNetwork, IPv6Interface)):
return (u'%s/%d' % (u':'.join(parts), self._prefixlen))
return u':'.join(parts)
|
'Return the reverse DNS pointer name for the IPv6 address.
This implements the method described in RFC3596 2.5.'
| def _reverse_pointer(self):
| reverse_chars = self.exploded[::(-1)].replace(u':', u'')
return (u'.'.join(reverse_chars) + u'.ip6.arpa')
|
'Instantiate a new IPv6 address object.
Args:
address: A string or integer representing the IP
Additionally, an integer can be passed, so
IPv6Address(\'2001:db8::\') ==
IPv6Address(42540766411282592856903984951653826560)
or, more generally
IPv6Address(int(IPv6Address(\'2001:db8::\'))) ==
IPv6Address(\'2001:db8::\')
Raises:
AddressValueError: If address isn\'t a valid IPv6 address.'
| def __init__(self, address):
| if isinstance(address, _compat_int_types):
self._check_int_address(address)
self._ip = address
return
if isinstance(address, bytes):
self._check_packed_address(address, 16)
bvs = _compat_bytes_to_byte_vals(address)
self._ip = _compat_int_from_byte_vals(bvs, u'big')
return
addr_str = _compat_str(address)
if (u'/' in addr_str):
raise AddressValueError((u"Unexpected '/' in %r" % address))
self._ip = self._ip_int_from_string(addr_str)
|
'The binary representation of this address.'
| @property
def packed(self):
| return v6_int_to_packed(self._ip)
|
'Test if the address is reserved for multicast use.
Returns:
A boolean, True if the address is a multicast address.
See RFC 2373 2.7 for details.'
| @property
def is_multicast(self):
| return (self in self._constants._multicast_network)
|
'Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.'
| @property
def is_reserved(self):
| return any(((self in x) for x in self._constants._reserved_networks))
|
'Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is reserved per RFC 4291.'
| @property
def is_link_local(self):
| return (self in self._constants._linklocal_network)
|
'Test if the address is reserved for site-local.
Note that the site-local address space has been deprecated by RFC 3879.
Use is_private to test if this address is in the space of unique local
addresses as defined by RFC 4193.
Returns:
A boolean, True if the address is reserved per RFC 3513 2.5.6.'
| @property
def is_site_local(self):
| return (self in self._constants._sitelocal_network)
|
'Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv6-special-registry.'
| @property
def is_private(self):
| return any(((self in net) for net in self._constants._private_networks))
|
'Test if this address is allocated for public networks.
Returns:
A boolean, true if the address is not reserved per
iana-ipv6-special-registry.'
| @property
def is_global(self):
| return (not self.is_private)
|
'Test if the address is unspecified.
Returns:
A boolean, True if this is the unspecified address as defined in
RFC 2373 2.5.2.'
| @property
def is_unspecified(self):
| return (self._ip == 0)
|
'Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback address as defined in
RFC 2373 2.5.3.'
| @property
def is_loopback(self):
| return (self._ip == 1)
|
'Return the IPv4 mapped address.
Returns:
If the IPv6 address is a v4 mapped address, return the
IPv4 mapped address. Return None otherwise.'
| @property
def ipv4_mapped(self):
| if ((self._ip >> 32) != 65535):
return None
return IPv4Address((self._ip & 4294967295))
|
'Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn\'t appear to be a teredo address (doesn\'t start with
2001::/32)'
| @property
def teredo(self):
| if ((self._ip >> 96) != 536936448):
return None
return (IPv4Address(((self._ip >> 64) & 4294967295)), IPv4Address(((~ self._ip) & 4294967295)))
|
'Return the IPv4 6to4 embedded address.
Returns:
The IPv4 6to4-embedded address if present or None if the
address doesn\'t appear to contain a 6to4 embedded address.'
| @property
def sixtofour(self):
| if ((self._ip >> 112) != 8194):
return None
return IPv4Address(((self._ip >> 80) & 4294967295))
|
'Instantiate a new IPv6 Network object.
Args:
address: A string or integer representing the IPv6 network or the
IP and prefix/netmask.
\'2001:db8::/128\'
\'2001:db8:0000:0000:0000:0000:0000:0000/128\'
\'2001:db8::\'
are all functionally the same in IPv6. That is to say,
failing to provide a subnetmask will create an object with
a mask of /128.
Additionally, an integer can be passed, so
IPv6Network(\'2001:db8::\') ==
IPv6Network(42540766411282592856903984951653826560)
or, more generally
IPv6Network(int(IPv6Network(\'2001:db8::\'))) ==
IPv6Network(\'2001:db8::\')
strict: A boolean. If true, ensure that we have been passed
A true network address, eg, 2001:db8::1000/124 and not an
IP address on a network, eg, 2001:db8::1/124.
Raises:
AddressValueError: If address isn\'t a valid IPv6 address.
NetmaskValueError: If the netmask isn\'t valid for
an IPv6 address.
ValueError: If strict was True and a network address was not
supplied.'
| def __init__(self, address, strict=True):
| _BaseNetwork.__init__(self, address)
if isinstance(address, (bytes, _compat_int_types)):
self.network_address = IPv6Address(address)
(self.netmask, self._prefixlen) = self._make_netmask(self._max_prefixlen)
return
if isinstance(address, tuple):
if (len(address) > 1):
arg = address[1]
else:
arg = self._max_prefixlen
(self.netmask, self._prefixlen) = self._make_netmask(arg)
self.network_address = IPv6Address(address[0])
packed = int(self.network_address)
if ((packed & int(self.netmask)) != packed):
if strict:
raise ValueError((u'%s has host bits set' % self))
else:
self.network_address = IPv6Address((packed & int(self.netmask)))
return
addr = _split_optional_netmask(address)
self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
if (len(addr) == 2):
arg = addr[1]
else:
arg = self._max_prefixlen
(self.netmask, self._prefixlen) = self._make_netmask(arg)
if strict:
if (IPv6Address((int(self.network_address) & int(self.netmask))) != self.network_address):
raise ValueError((u'%s has host bits set' % self))
self.network_address = IPv6Address((int(self.network_address) & int(self.netmask)))
if (self._prefixlen == (self._max_prefixlen - 1)):
self.hosts = self.__iter__
|
'Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn\'t return the
Subnet-Router anycast address.'
| def hosts(self):
| network = int(self.network_address)
broadcast = int(self.broadcast_address)
for x in _compat_range((network + 1), (broadcast + 1)):
(yield self._address_class(x))
|
'Test if the address is reserved for site-local.
Note that the site-local address space has been deprecated by RFC 3879.
Use is_private to test if this address is in the space of unique local
addresses as defined by RFC 4193.
Returns:
A boolean, True if the address is reserved per RFC 3513 2.5.6.'
| @property
def is_site_local(self):
| return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
|
'Acquire the lock.
* If timeout is omitted (or None), wait forever trying to lock the
file.
* If timeout > 0, try to acquire the lock for that many seconds. If
the lock period expires and the file is still locked, raise
LockTimeout.
* If timeout <= 0, raise AlreadyLocked immediately if the file is
already locked.'
| def acquire(self, timeout=None):
| raise NotImplemented('implement in subclass')
|
'Release the lock.
If the file is not locked, raise NotLocked.'
| def release(self):
| raise NotImplemented('implement in subclass')
|
'Context manager support.'
| def __enter__(self):
| self.acquire()
return self
|
'Context manager support.'
| def __exit__(self, *_exc):
| self.release()
|
'>>> lock = LockBase(\'somefile\')
>>> lock = LockBase(\'somefile\', threaded=False)'
| def __init__(self, path, threaded=True, timeout=None):
| super(LockBase, self).__init__(path)
self.lock_file = (os.path.abspath(path) + '.lock')
self.hostname = socket.gethostname()
self.pid = os.getpid()
if threaded:
t = threading.current_thread()
ident = getattr(t, 'ident', hash(t))
self.tname = ('-%x' % (ident & 4294967295))
else:
self.tname = ''
dirname = os.path.dirname(self.lock_file)
self.unique_name = os.path.join(dirname, ('%s%s.%s%s' % (self.hostname, self.tname, self.pid, hash(self.path))))
self.timeout = timeout
|
'Tell whether or not the file is locked.'
| def is_locked(self):
| raise NotImplemented('implement in subclass')
|
'Return True if this object is locking the file.'
| def i_am_locking(self):
| raise NotImplemented('implement in subclass')
|
'Remove a lock. Useful if a locking thread failed to unlock.'
| def break_lock(self):
| raise NotImplemented('implement in subclass')
|
'Get the PID from the lock file.'
| def read_pid(self):
| return read_pid_from_pidfile(self.path)
|
'Test if the lock is currently held.
The lock is held if the PID file for this lock exists.'
| def is_locked(self):
| return os.path.exists(self.path)
|
'Test if the lock is held by the current process.
Returns ``True`` if the current process ID matches the
number stored in the PID file.'
| def i_am_locking(self):
| return (self.is_locked() and (os.getpid() == self.read_pid()))
|
'Acquire the lock.
Creates the PID file for this lock, or raises an error if
the lock could not be acquired.'
| def acquire(self, timeout=None):
| timeout = (timeout if (timeout is not None) else self.timeout)
end_time = time.time()
if ((timeout is not None) and (timeout > 0)):
end_time += timeout
while True:
try:
write_pid_to_pidfile(self.path)
except OSError as exc:
if (exc.errno == errno.EEXIST):
if (time.time() > end_time):
if ((timeout is not None) and (timeout > 0)):
raise LockTimeout(('Timeout waiting to acquire lock for %s' % self.path))
else:
raise AlreadyLocked(('%s is already locked' % self.path))
time.sleep((((timeout is not None) and (timeout / 10)) or 0.1))
else:
raise LockFailed(('failed to create %s' % self.path))
else:
return
|
'Release the lock.
Removes the PID file to release the lock, or raises an
error if the current process does not hold the lock.'
| def release(self):
| if (not self.is_locked()):
raise NotLocked(('%s is not locked' % self.path))
if (not self.i_am_locking()):
raise NotMyLock(('%s is locked, but not by me' % self.path))
remove_existing_pidfile(self.path)
|
'Break an existing lock.
Removes the PID file if it already exists, otherwise does
nothing.'
| def break_lock(self):
| remove_existing_pidfile(self.path)
|
'>>> lock = MkdirLockFile(\'somefile\')
>>> lock = MkdirLockFile(\'somefile\', threaded=False)'
| def __init__(self, path, threaded=True, timeout=None):
| LockBase.__init__(self, path, threaded, timeout)
self.unique_name = os.path.join(self.lock_file, ('%s.%s%s' % (self.hostname, self.tname, self.pid)))
|
'>>> lock = SQLiteLockFile(\'somefile\')
>>> lock = SQLiteLockFile(\'somefile\', threaded=False)'
| def __init__(self, path, threaded=True, timeout=None):
| LockBase.__init__(self, path, threaded, timeout)
self.lock_file = unicode(self.lock_file)
self.unique_name = unicode(self.unique_name)
if (SQLiteLockFile.testdb is None):
import tempfile
(_fd, testdb) = tempfile.mkstemp()
os.close(_fd)
os.unlink(testdb)
del _fd, tempfile
SQLiteLockFile.testdb = testdb
import sqlite3
self.connection = sqlite3.connect(SQLiteLockFile.testdb)
c = self.connection.cursor()
try:
c.execute('create table locks( lock_file varchar(32), unique_name varchar(32))')
except sqlite3.OperationalError:
pass
else:
self.connection.commit()
import atexit
atexit.register(os.unlink, SQLiteLockFile.testdb)
|
'supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text'
| def __getattr__(self, aname):
| if (aname == 'lineno'):
return lineno(self.loc, self.pstr)
elif (aname in ('col', 'column')):
return col(self.loc, self.pstr)
elif (aname == 'line'):
return line(self.loc, self.pstr)
else:
raise AttributeError(aname)
|
'Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.'
| def markInputline(self, markerString='>!<'):
| line_str = self.line
line_column = (self.column - 1)
if markerString:
line_str = ''.join((line_str[:line_column], markerString, line_str[line_column:]))
return line_str.strip()
|
'Returns all named result keys.'
| def iterkeys(self):
| if hasattr(self.__tokdict, 'iterkeys'):
return self.__tokdict.iterkeys()
else:
return iter(self.__tokdict)
|
'Returns all named result values.'
| def itervalues(self):
| return (self[k] for k in self.iterkeys())
|
'Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names.'
| def haskeys(self):
| return bool(self.__tokdict)
|
'Removes and returns item at specified index (default=last).
Supports both list and dict semantics for pop(). If passed no
argument or an integer argument, it will use list semantics
and pop tokens from the list of parsed tokens. If passed a
non-integer argument (most likely a string), it will use dict
semantics and pop the corresponding value from any defined
results names. A second default return value argument is
supported, just as in dict.pop().'
| def pop(self, *args, **kwargs):
| if (not args):
args = [(-1)]
for (k, v) in kwargs.items():
if (k == 'default'):
args = (args[0], v)
else:
raise TypeError(("pop() got an unexpected keyword argument '%s'" % k))
if (isinstance(args[0], int) or (len(args) == 1) or (args[0] in self)):
index = args[0]
ret = self[index]
del self[index]
return ret
else:
defaultvalue = args[1]
return defaultvalue
|
'Returns named result matching the given key, or if there is no
such name, then returns the given C{defaultValue} or C{None} if no
C{defaultValue} is specified.'
| def get(self, key, defaultValue=None):
| if (key in self):
return self[key]
else:
return defaultValue
|
'Inserts new element at location index in the list of parsed tokens.'
| def insert(self, index, insStr):
| self.__toklist.insert(index, insStr)
for (name, occurrences) in self.__tokdict.items():
for (k, (value, position)) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, (position + (position > index)))
|
'Add single element to end of ParseResults list of elements.'
| def append(self, item):
| self.__toklist.append(item)
|
'Add sequence of elements to end of ParseResults list of elements.'
| def extend(self, itemseq):
| if isinstance(itemseq, ParseResults):
self += itemseq
else:
self.__toklist.extend(itemseq)
|
'Clear all elements and results names.'
| def clear(self):
| del self.__toklist[:]
self.__tokdict.clear()
|
'Returns the parse results as a nested list of matching tokens, all converted to strings.'
| def asList(self):
| return [(res.asList() if isinstance(res, ParseResults) else res) for res in self.__toklist]
|
'Returns the named parse results as a nested dictionary.'
| def asDict(self):
| if PY_3:
item_fn = self.items
else:
item_fn = self.iteritems
return dict((((k, v.asDict()) if isinstance(v, ParseResults) else (k, v)) for (k, v) in item_fn()))
|
'Returns a new copy of a C{ParseResults} object.'
| def copy(self):
| ret = ParseResults(self.__toklist)
ret.__tokdict = self.__tokdict.copy()
ret.__parent = self.__parent
ret.__accumNames.update(self.__accumNames)
ret.__name = self.__name
return ret
|
'Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.'
| def asXML(self, doctag=None, namedItemsOnly=False, indent='', formatted=True):
| nl = '\n'
out = []
namedItems = dict(((v[1], k) for (k, vlist) in self.__tokdict.items() for v in vlist))
nextLevelIndent = (indent + ' ')
if (not formatted):
indent = ''
nextLevelIndent = ''
nl = ''
selfTag = None
if (doctag is not None):
selfTag = doctag
elif self.__name:
selfTag = self.__name
if (not selfTag):
if namedItemsOnly:
return ''
else:
selfTag = 'ITEM'
out += [nl, indent, '<', selfTag, '>']
for (i, res) in enumerate(self.__toklist):
if isinstance(res, ParseResults):
if (i in namedItems):
out += [res.asXML(namedItems[i], (namedItemsOnly and (doctag is None)), nextLevelIndent, formatted)]
else:
out += [res.asXML(None, (namedItemsOnly and (doctag is None)), nextLevelIndent, formatted)]
else:
resTag = None
if (i in namedItems):
resTag = namedItems[i]
if (not resTag):
if namedItemsOnly:
continue
else:
resTag = 'ITEM'
xmlBodyText = _xml_escape(_ustr(res))
out += [nl, nextLevelIndent, '<', resTag, '>', xmlBodyText, '</', resTag, '>']
out += [nl, indent, '</', selfTag, '>']
return ''.join(out)
|
'Returns the results name for this token expression.'
| def getName(self):
| if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif ((len(self) == 1) and (len(self.__tokdict) == 1) and (self.__tokdict.values()[0][0][1] in (0, (-1)))):
return self.__tokdict.keys()[0]
else:
return None
|
'Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data.'
| def dump(self, indent='', depth=0):
| out = []
NL = '\n'
out.append((indent + _ustr(self.asList())))
if self.haskeys():
items = sorted(self.items())
for (k, v) in items:
if out:
out.append(NL)
out.append(('%s%s- %s: ' % (indent, (' ' * depth), k)))
if isinstance(v, ParseResults):
if v:
out.append(v.dump(indent, (depth + 1)))
else:
out.append(_ustr(v))
else:
out.append(_ustr(v))
elif any((isinstance(vv, ParseResults) for vv in self)):
v = self
for (i, vv) in enumerate(v):
if isinstance(vv, ParseResults):
out.append(('\n%s%s[%d]:\n%s%s%s' % (indent, (' ' * depth), i, indent, (' ' * (depth + 1)), vv.dump(indent, (depth + 1)))))
else:
out.append(('\n%s%s[%d]:\n%s%s%s' % (indent, (' ' * depth), i, indent, (' ' * (depth + 1)), _ustr(vv))))
return ''.join(out)
|
'Pretty-printer for parsed results as a list, using the C{pprint} module.
Accepts additional positional or keyword args as defined for the
C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})'
| def pprint(self, *args, **kwargs):
| pprint.pprint(self.asList(), *args, **kwargs)
|
'Overrides the default whitespace chars'
| @staticmethod
def setDefaultWhitespaceChars(chars):
| ParserElement.DEFAULT_WHITE_CHARS = chars
|
'Set class to be used for inclusion of string literals into a parser.'
| @staticmethod
def inlineLiteralsUsing(cls):
| ParserElement.literalStringClass = cls
|
'Make a copy of this C{ParserElement}. Useful for defining different parse actions
for the same parsing pattern, using copies of the original parse element.'
| def copy(self):
| cpy = copy.copy(self)
cpy.parseAction = self.parseAction[:]
cpy.ignoreExprs = self.ignoreExprs[:]
if self.copyDefaultWhiteChars:
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
return cpy
|
'Define name for this expression, for use in debugging.'
| def setName(self, name):
| self.name = name
self.errmsg = ('Expected ' + self.name)
if hasattr(self, 'exception'):
self.exception.msg = self.errmsg
return self
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.