wildcard.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # -*- coding: utf-8 -*-
  2. """Support for wildcard pattern matching in object inspection.
  3. Authors
  4. -------
  5. - Jörgen Stenarson <jorgen.stenarson@bostream.nu>
  6. - Thomas Kluyver
  7. """
  8. #*****************************************************************************
  9. # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
  10. #
  11. # Distributed under the terms of the BSD License. The full license is in
  12. # the file COPYING, distributed as part of this software.
  13. #*****************************************************************************
  14. import re
  15. import types
  16. from IPython.utils.dir2 import dir2
  17. def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
  18. """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
  19. objects from the types package, and vice versa."""
  20. typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
  21. typestr2type, type2typestr = {}, {}
  22. for tname in typenamelist:
  23. name = tname[:-4].lower() # Cut 'Type' off the end of the name
  24. obj = getattr(types, tname)
  25. typestr2type[name] = obj
  26. if name not in dont_include_in_type2typestr:
  27. type2typestr[obj] = name
  28. return typestr2type, type2typestr
  29. typestr2type, type2typestr = create_typestr2type_dicts()
  30. def is_type(obj, typestr_or_type):
  31. """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
  32. can take strings or actual python types for the second argument, i.e.
  33. 'tuple'<->TupleType. 'all' matches all types.
  34. TODO: Should be extended for choosing more than one type."""
  35. if typestr_or_type == "all":
  36. return True
  37. if type(typestr_or_type) == type:
  38. test_type = typestr_or_type
  39. else:
  40. test_type = typestr2type.get(typestr_or_type, False)
  41. if test_type:
  42. return isinstance(obj, test_type)
  43. return False
  44. def show_hidden(str, show_all=False):
  45. """Return true for strings starting with single _ if show_all is true."""
  46. return show_all or str.startswith("__") or not str.startswith("_")
  47. def dict_dir(obj):
  48. """Produce a dictionary of an object's attributes. Builds on dir2 by
  49. checking that a getattr() call actually succeeds."""
  50. ns = {}
  51. for key in dir2(obj):
  52. # This seemingly unnecessary try/except is actually needed
  53. # because there is code out there with metaclasses that
  54. # create 'write only' attributes, where a getattr() call
  55. # will fail even if the attribute appears listed in the
  56. # object's dictionary. Properties can actually do the same
  57. # thing. In particular, Traits use this pattern
  58. try:
  59. ns[key] = getattr(obj, key)
  60. except AttributeError:
  61. pass
  62. return ns
  63. def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
  64. show_all=True):
  65. """Filter a namespace dictionary by name pattern and item type."""
  66. pattern = name_pattern.replace("*",".*").replace("?",".")
  67. if ignore_case:
  68. reg = re.compile(pattern+"$", re.I)
  69. else:
  70. reg = re.compile(pattern+"$")
  71. # Check each one matches regex; shouldn't be hidden; of correct type.
  72. return dict((key,obj) for key, obj in ns.items() if reg.match(key) \
  73. and show_hidden(key, show_all) \
  74. and is_type(obj, type_pattern) )
  75. def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
  76. """Return dictionary of all objects in a namespace dictionary that match
  77. type_pattern and filter."""
  78. pattern_list=filter.split(".")
  79. if len(pattern_list) == 1:
  80. return filter_ns(namespace, name_pattern=pattern_list[0],
  81. type_pattern=type_pattern,
  82. ignore_case=ignore_case, show_all=show_all)
  83. else:
  84. # This is where we can change if all objects should be searched or
  85. # only modules. Just change the type_pattern to module to search only
  86. # modules
  87. filtered = filter_ns(namespace, name_pattern=pattern_list[0],
  88. type_pattern="all",
  89. ignore_case=ignore_case, show_all=show_all)
  90. results = {}
  91. for name, obj in filtered.items():
  92. ns = list_namespace(dict_dir(obj), type_pattern,
  93. ".".join(pattern_list[1:]),
  94. ignore_case=ignore_case, show_all=show_all)
  95. for inner_name, inner_obj in ns.items():
  96. results["%s.%s"%(name,inner_name)] = inner_obj
  97. return results