wildcard.py 4.5 KB

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