"Steven D'Aprano" firstname.lastname@example.org wrote in message news:email@example.com...
Just throwing a suggestion out there...
def atomic(obj, _atomic=(basestring,)): try: return bool(obj.__atomic__) except AttributeError: if isinstance(obj, _atomic): return True else: try: iter(obj) except TypeError: return True return False
assert atomic("abc") assert not atomic(['a', 'b', 'c'])
If built-in objects grew an __atomic__ attribute, you could simplify the atomic() function greatly:
def atomic(obj): return bool(obj.__atomic__)
However atomic() is defined, now flatten() is easy:
def flatten(obj): if atomic(obj): yield obj else: for item in obj: for i in flatten(item): yield i
If you needed more control, you could customise it using standard techniques e.g. shadow the atomic() function with your own version, sub-class the types you wish to treat differently, make __atomic__ a
This is a lot of work to avoid being explicit about either atomic or non-atomic classes on an site, package, module, or call basis ;-)