I use data types to assert unique values in python 2 and 3. Otherwise I cant make them work like a str or int types. However if you need to check a value that can have any type except a specific one, then they are mighty useful and make code read better.
Inherit object will make a type in python.
class unset(object):
pass
>>> print type(unset)
<type 'type'>
Example Use: you might want to conditionally filter or print a value using a condition or a function handler so using a type as a default value will be useful.
from __future__ import print_function # make python2/3 compatible
class unset(object):
pass
def some_func(a,b, show_if=unset):
result = a + b
## just return it
if show_if is unset:
return result
## handle show_if to conditionally output something
if hasattr(show_if,'__call__'):
if show_if(result):
print( "show_if %s = %s" % ( show_if.__name__ , result ))
elif show_if:
print(show_if, " condition met ", result)
return result
print("Are > 5)")
for i in range(10):
result = some_func(i,2, show_if= i>5 )
def is_even(val):
return not val % 2
print("Are even")
for i in range(10):
result = some_func(i,2, show_if= is_even )
Output
Are > 5)
True condition met 8
True condition met 9
True condition met 10
True condition met 11
Are even
show_if is_even = 2
show_if is_even = 4
show_if is_even = 6
show_if is_even = 8
show_if is_even = 10
if show_if=unset
is perfect use case for this because its safer and reads well. I have also used them in enums which are not really a thing in python.