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