Returns the type of each object in the given object. - For modules, this means classes and functions etc. - For list and tuples, means the type of each item in it. - For other objects, means the type of the object itself.
(object, quantify=True, replace=readable_types)
| 361 | ) |
| 362 | |
| 363 | def reflect(object, quantify=True, replace=readable_types): |
| 364 | """ Returns the type of each object in the given object. |
| 365 | - For modules, this means classes and functions etc. |
| 366 | - For list and tuples, means the type of each item in it. |
| 367 | - For other objects, means the type of the object itself. |
| 368 | """ |
| 369 | _type = lambda object: type(object).__name__ |
| 370 | types = [] |
| 371 | # Classes and modules with a __dict__ attribute listing methods, functions etc. |
| 372 | if hasattr(object, "__dict__"): |
| 373 | # Function and method objects. |
| 374 | if _type(object) in ("function", "instancemethod"): |
| 375 | types.append(_type(object)) |
| 376 | # Classes and modules. |
| 377 | else: |
| 378 | for v in object.__dict__.values(): |
| 379 | try: types.append(str(v.__classname__)) |
| 380 | except: |
| 381 | # Not a class after all (some stuff like ufunc in Numeric). |
| 382 | types.append(_type(v)) |
| 383 | # Lists and tuples can consist of several types of objects. |
| 384 | elif isinstance(object, (list, tuple, set)): |
| 385 | types += [_type(x) for x in object] |
| 386 | # Dictionaries have keys pointing to objects. |
| 387 | elif isinstance(object, dict): |
| 388 | types += [_type(k) for k in object] |
| 389 | types += [_type(v) for v in object.values()] |
| 390 | else: |
| 391 | types.append(_type(object)) |
| 392 | # Clean up type strings. |
| 393 | m = {} |
| 394 | for i in range(len(types)): |
| 395 | k = types[i] |
| 396 | # Execute the regular expressions once only, |
| 397 | # next time we'll have the conversion cached. |
| 398 | if k not in m: |
| 399 | for a,b in replace: |
| 400 | types[i] = re.sub(a, b, types[i]) |
| 401 | m[k] = types[i] |
| 402 | types[i] = m[k] |
| 403 | if not quantify: |
| 404 | if not isinstance(object, (list, tuple, set, dict)) and not hasattr(object, "__dict__"): |
| 405 | return types[0] |
| 406 | return types |
| 407 | return count(types, plural={"built-in function" : "built-in functions"}) |
| 408 | |
| 409 | #print reflect("hello") |
| 410 | #print reflect(["hello", "goobye"]) |