from random import random
def to_color(obj=None):
"""Determine a color (string 000000-ffffff) from the hash of any object
If no argument is passed, a random color is returned.
Args:
obj: any hashable object; string, tuple, ...
Returns:
a color string in range '000000' to 'ffffff'
"""
obj = obj if obj else random()
return "{0:06x}".format(abs(hash(obj)))
My questions:
- Is the line
obj = obj if obj else random()
idiomatic? - Is
hash(obj)
the "proper" way to get a deterministic yet scrambled string for my purpose? - The
abs
takes care of negative hash values (e.g. from hashing negative integers). Is there a better way which doesn't collide so easily for small (absolute) integer values? (Right now,to_color(500)
is equal toto_color(-500)
.)