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