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