[Python-Dev] Iterable String Redux (aka String ABC) (original) (raw)
Terry Reedy tjreedy at udel.edu
Wed May 28 05:15:53 CEST 2008
- Previous message: [Python-Dev] Iterable String Redux (aka String ABC)
- Next message: [Python-Dev] Iterable String Redux (aka String ABC)
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
"Steven D'Aprano" <steve at pearwood.info> wrote in message news:200805281007.59902.steve at pearwood.info...
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 computed property instead of a simple attribute, etc.
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 ;-)
- Previous message: [Python-Dev] Iterable String Redux (aka String ABC)
- Next message: [Python-Dev] Iterable String Redux (aka String ABC)
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]