Skip to content

Instantly share code, notes, and snippets.

@giwa
Last active August 29, 2015 14:07
Show Gist options
  • Save giwa/5f6f1b35d5c823600a0d to your computer and use it in GitHub Desktop.
Save giwa/5f6f1b35d5c823600a0d to your computer and use it in GitHub Desktop.
Identify type of string.
# Provide function to identify the data type
import socket
class TypeIdentifer(object):
_identifers=list()
@staticmethod
def is_int(s):
"""
Check if this is int
>>> ti.is_int(10)
True
>>> ti.is_int("10")
True
>>> ti.is_int(10.1)
False
>>> ti.is_int("10.1")
False
"""
if isinstance(s, int):
return True
if isinstance(s, float):
return False
try:
int(s)
return True
except:
return False
@staticmethod
def is_float(s):
"""
Check if this is float
>>> ti.is_float(10.1)
True
>>> ti.is_float("10.1")
True
>>> ti.is_float(10)
False
>>> ti.is_float("10")
False
"""
if isinstance(s, int):
return False
if isinstance(s, float):
return True
try:
int(s)
return False
except ValueError:
pass
try:
float(s)
return True
except ValueError:
return False
@staticmethod
def is_ipv4(s):
"""
Check if this is ipv4
>>> ti.is_ipv4("10.24.1.1")
True
>>> ti.is_ipv4("10.24.1.300")
False
>>> ti.is_ipv4("10.1")
False
>>> ti.is_ipv4("10.24.1.1/30")
False
>>> ti.is_ipv4("10.24.1.1:80")
False
"""
try:
socket.inet_pton(socket.AF_INET, s)
except AttributeError:
try:
socket.inet_aton(s)
except socket.error:
return False
return s.count('.') == 3
except socket.error:
return False
return True
@staticmethod
def is_ipv6(s):
"""
Check if this is ipv6
>>> ti.is_ipv6("FE80:0000:0000:0000:0202:B3FF:FE1E:8329")
True
>>> ti.is_ipv6("FE80::0202:B3FF:FE1E:8329")
True
>>> ti.is_ipv6("::0")
True
>>> ti.is_ipv6("::")
True
>>> ti.is_ipv6("::1")
True
>>> ti.is_ipv6("FE80::0202:B3FF:FE1E:8329:80")
True
>>> ti.is_ipv6("FE80:0000:0000:0000:0202:B3FF:FE1E:8329:80")
False
"""
try:
socket.inet_pton(socket.AF_INET6, s)
except socket.error:
return False
return True
@staticmethod
def is_str(s):
return isinstance(s, str)
@classmethod
def identify(cls, s):
"""
Identify data type
>>> ti.identify("10")
'int'
>>> ti.identify("10.1")
'float'
>>> ti.identify("10.1.1.1")
'ipv4'
>>> ti.identify("E80::0202:B3FF:FE1E:8329:80")
'ipv6'
>>> ti.identify("foo")
'str'
"""
cls._load_identifer()
for f in cls._identifers:
if f(s):
data_type = f.__name__
return data_type[data_type.index("_")+1:]
else:
continue
else:
return "str"
@classmethod
def _load_identifer(cls):
cls._identifers.extend([cls.is_int,
cls.is_float,
cls.is_ipv4,
cls.is_ipv6])
def _test():
import doctest
globs = globals().copy()
globs['ti'] = TypeIdentifer()
(failure_count, test_count) = doctest.testmod(
globs=globs, optionflags=doctest.ELLIPSIS)
if failure_count:
exit(-1)
if __name__ == "__main__":
_test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment