##// END OF EJS Templates
Safe isinstance for unloaded modules
Joel Nothman -
Show More
@@ -98,20 +98,6 b' else:'
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
99
99
100
100
101 # For dict key completion
102 try:
103 import numpy
104 except ImportError:
105 STRUCT_ARRAY_TYPES = ()
106 else:
107 STRUCT_ARRAY_TYPES = (numpy.ndarray,)
108 try:
109 import pandas
110 except ImportError:
111 KEYED_DICT_TYPES = (dict,)
112 else:
113 KEYED_DICT_TYPES = (dict, pandas.DataFrame)
114
115 #-----------------------------------------------------------------------------
101 #-----------------------------------------------------------------------------
116 # Main functions and classes
102 # Main functions and classes
117 #-----------------------------------------------------------------------------
103 #-----------------------------------------------------------------------------
@@ -489,6 +475,13 b' def match_dict_keys(keys, prefix):'
489 return quote, matched
475 return quote, matched
490
476
491
477
478 def _safe_isinstance(obj, module, class_name):
479 """Checks if obj is an instance of module.class_name if loaded
480 """
481 return (module in sys.modules and
482 isinstance(obj, getattr(__import__(module), class_name)))
483
484
492
485
493 class IPCompleter(Completer):
486 class IPCompleter(Completer):
494 """Extension of the completer class with IPython-specific features"""
487 """Extension of the completer class with IPython-specific features"""
@@ -872,12 +865,13 b' class IPCompleter(Completer):'
872 def dict_key_matches(self, text):
865 def dict_key_matches(self, text):
873 def get_keys(obj):
866 def get_keys(obj):
874 # Only allow completion for known in-memory dict-like types
867 # Only allow completion for known in-memory dict-like types
875 if isinstance(obj, KEYED_DICT_TYPES):
868 if isinstance(obj, dict) or\
869 _safe_isinstance(obj, 'pandas', 'DataFrame'):
876 try:
870 try:
877 return list(obj.keys())
871 return list(obj.keys())
878 except Exception:
872 except Exception:
879 return []
873 return []
880 elif isinstance(obj, STRUCT_ARRAY_TYPES):
874 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
881 return obj.dtype.names or []
875 return obj.dtype.names or []
882 return []
876 return []
883
877
General Comments 0
You need to be logged in to leave comments. Login now