def get_trait_names(): global TRAIT_NAMES from enthought.traits.api import HasTraits if TRAIT_NAMES is None: TRAIT_NAMES = set(dir2(HasTraits())) - set(dir2(object())) else: return TRAIT_NAMES
def get_trait_names(): global TRAIT_NAMES from enthought.traits.api import HasTraits if TRAIT_NAMES is None: TRAIT_NAMES = set( dir2(HasTraits()) ) - set( dir2(object()) ) else: return TRAIT_NAMES
def pymvpa_completer(self, event): """A custom IPython tab-completer that is collections-aware. """ symbol_parts = event.symbol.split('.') base = '.'.join(symbol_parts[:-1]) oinfo = self._ofind(base) if not oinfo['found']: raise TryNext obj = oinfo['obj'] # OK, we got the object. See if it's traits, else punt if not isinstance(obj, col.Collection): #print "exiting for %s" % obj raise TryNext # it's a Collection object, lets add its keys attrs = dir2(obj) #print "adding ", obj.keys() attrs += list(obj.keys()) # Let's also respect the user's readline_omit__names setting: omit__names = ipget().IP.Completer.omit__names if omit__names == 1: attrs = [a for a in attrs if not a.startswith('__')] elif omit__names == 2: attrs = [a for a in attrs if not a.startswith('_')] # The base of the completion, so we can form the final results list bdot = base+'.' tcomp = [bdot+a for a in attrs] return tcomp
def __init__(self,obj,name_pattern="*",type_pattern="all",ignore_case=True, show_all=True): self.show_all = show_all #Hide names beginning with single _ self.object = obj self.name_pattern = name_pattern self.type_pattern = type_pattern self.ignore_case = ignore_case # We should only match EXACT dicts here, so DON'T use isinstance() if type(obj) == types.DictType: self._ns = obj else: kv = [] for key in dir2(obj): if isinstance(key, basestring): # This seemingly unnecessary try/except is actually needed # because there is code out there with metaclasses that # create 'write only' attributes, where a getattr() call # will fail even if the attribute appears listed in the # object's dictionary. Properties can actually do the same # thing. In particular, Traits use this pattern try: kv.append((key,getattr(obj,key))) except AttributeError: pass self._ns = dict(kv)
def isis_completers(self, event): """ This should return a list of strings with possible completions. """ symbol_parts = event.symbol.split('.') base = '.'.join(symbol_parts[:-1]) oinfo = self._ofind(base) if not oinfo['found']: raise TryNext obj = oinfo['obj'] types = (pyisis.files.IsisCollection, pyisis.files.MasterFile, pyisis.records.MasterRecord, pyisis.fields.MasterField, pyisis.fields.MasterContainerField, pyisis.records.XrfRecord) if not any((isinstance(obj, i) for i in types)): raise TryNext attrs = dir2(obj) attrs = [a for a in attrs if not a.startswith('__')] # The base of the completion, so we can form the final results list bdot = base+'.' tcomp = [bdot+a for a in attrs] return tcomp
def __init__(self, obj, name_pattern="*", type_pattern="all", ignore_case=True, show_all=True): self.show_all = show_all #Hide names beginning with single _ self.object = obj self.name_pattern = name_pattern self.type_pattern = type_pattern self.ignore_case = ignore_case # We should only match EXACT dicts here, so DON'T use isinstance() if type(obj) == types.DictType: self._ns = obj else: kv = [] for key in dir2(obj): if isinstance(key, basestring): # This seemingly unnecessary try/except is actually needed # because there is code out there with metaclasses that # create 'write only' attributes, where a getattr() call # will fail even if the attribute appears listed in the # object's dictionary. Properties can actually do the same # thing. In particular, Traits use this pattern try: kv.append((key, getattr(obj, key))) except AttributeError: pass self._ns = dict(kv)
def pymvpa_completer(self, event): """A custom IPython tab-completer that is collections-aware. """ symbol_parts = event.symbol.split(".") base = ".".join(symbol_parts[:-1]) oinfo = self._ofind(base) if not oinfo["found"]: raise TryNext obj = oinfo["obj"] # OK, we got the object. See if it's traits, else punt if not isinstance(obj, col.Collection): # print "exiting for %s" % obj raise TryNext # it's a Collection object, lets add its keys attrs = dir2(obj) # print "adding ", obj.keys() attrs += obj.keys() # Let's also respect the user's readline_omit__names setting: omit__names = ipget().IP.Completer.omit__names if omit__names == 1: attrs = [a for a in attrs if not a.startswith("__")] elif omit__names == 2: attrs = [a for a in attrs if not a.startswith("_")] # The base of the completion, so we can form the final results list bdot = base + "." tcomp = [bdot + a for a in attrs] return tcomp
def trait_completer(self,event): """A custom IPython tab-completer that is traits-aware. It tries to hide the internal traits attributes, and reveal them only when it can reasonably guess that the user really is after one of them. """ #print '\nevent is:',event # dbg symbol_parts = event.symbol.split('.') base = '.'.join(symbol_parts[:-1]) #print 'base:',base # dbg oinfo = self._ofind(base) if not oinfo['found']: raise TryNext obj = oinfo['obj'] # OK, we got the object. See if it's traits, else punt if not looks_like_isinstance(obj, 'HasTraits'): raise TryNext # Defer import until here so as not to require Traits until we get something # that looks like it might be a HasTraits instance. from enthought.traits.api import HasTraits if not isinstance(obj, HasTraits): raise TryNext # it's a traits object, don't show the tr* attributes unless the completion # begins with 'tr' attrs = dir2(obj) # Now, filter out the attributes that start with the user's request attr_start = symbol_parts[-1] if attr_start: attrs = [a for a in attrs if a.startswith(attr_start)] # Let's also respect the user's readline_omit__names setting: omit__names = ipget().options.readline_omit__names if omit__names == 1: attrs = [a for a in attrs if not a.startswith('__')] elif omit__names == 2: attrs = [a for a in attrs if not a.startswith('_')] #print '\nastart:<%r>' % attr_start # dbg if len(attr_start)<COMPLETE_THRESHOLD: attrs = list(set(attrs) - get_trait_names()) # The base of the completion, so we can form the final results list bdot = base+'.' tcomp = [bdot+a for a in attrs] #print 'tcomp:',tcomp return tcomp
def trait_completer(self, event): """A custom IPython tab-completer that is traits-aware. It tries to hide the internal traits attributes, and reveal them only when it can reasonably guess that the user really is after one of them. """ #print '\nevent is:',event # dbg symbol_parts = event.symbol.split('.') base = '.'.join(symbol_parts[:-1]) #print 'base:',base # dbg oinfo = self._ofind(base) if not oinfo['found']: raise TryNext obj = oinfo['obj'] # OK, we got the object. See if it's traits, else punt if not looks_like_isinstance(obj, 'HasTraits'): raise TryNext # Defer import until here so as not to require Traits until we get something # that looks like it might be a HasTraits instance. from enthought.traits.api import HasTraits if not isinstance(obj, HasTraits): raise TryNext # it's a traits object, don't show the tr* attributes unless the completion # begins with 'tr' attrs = dir2(obj) # Now, filter out the attributes that start with the user's request attr_start = symbol_parts[-1] if attr_start: attrs = [a for a in attrs if a.startswith(attr_start)] # Let's also respect the user's readline_omit__names setting: omit__names = ipget().options.readline_omit__names if omit__names == 1: attrs = [a for a in attrs if not a.startswith('__')] elif omit__names == 2: attrs = [a for a in attrs if not a.startswith('_')] #print '\nastart:<%r>' % attr_start # dbg if len(attr_start) < COMPLETE_THRESHOLD: attrs = list(set(attrs) - get_trait_names()) # The base of the completion, so we can form the final results list bdot = base + '.' tcomp = [bdot + a for a in attrs] #print 'tcomp:',tcomp return tcomp
def attr_matches(self, text): """Compute matches when text contains a dot. MONKEYPATCHED VERSION (ipy_greedycompleter.py) Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ import re force_complete = 1 # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if m: expr, attr = m.group(1, 3) else: # force match - eval anything that ends with colon if not force_complete: return [] m2 = re.match(r"(.+)\.(\w*)$", self.lbuf) if not m2: return [] expr, attr = m2.group(1,2) try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] words = dir2(obj) try: words = generics.complete_object(obj, words) except ipapi.TryNext: pass # Build match list to return n = len(attr) res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] return res
def attr_matches(self, text): """Compute matches when text contains a dot. MONKEYPATCHED VERSION (ipy_greedycompleter.py) Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ import re force_complete = 1 # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if m: expr, attr = m.group(1, 3) else: # force match - eval anything that ends with colon if not force_complete: return [] m2 = re.match(r"(.+)\.(\w*)$", self.lbuf) if not m2: return [] expr, attr = m2.group(1, 2) try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] words = dir2(obj) try: words = generics.complete_object(obj, words) except ipapi.TryNext: pass # Build match list to return n = len(attr) res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr] return res
def remote_completer(self, event): """A custom IPython tab-completer. """ """Brian says: Here is what I have so far: def px_completer(self, event): # print event activeController = self.activeController keys = activeController.keys(0)[0] return keys I need to replace the keys = activeController ... line by something that 1) Instantiates an object in the engine namespace that has a complete method . 2) has a complete method that I can call like activateController.execute('results = __completer.complete(%s)' % s) activeController.pull(0, 'results') """ #print '\nevent is:',event # dbg symbol_parts = event.symbol.split('.') base = '.'.join(symbol_parts[:-1]) #print 'base:',base # dbg oinfo = self._ofind(base) if not oinfo['found']: raise TryNext obj = oinfo['obj'] # OK, we got the object. See if it's traits, else punt if not isinstance(obj, T.HasTraits): raise TryNext # it's a traits object, don't show the tr* attributes unless the completion # begins with 'tr' attrs = dir2(obj) # Now, filter out the attributes that start with the user's request attr_start = symbol_parts[-1] if attr_start: attrs = [a for a in attrs if a.startswith(attr_start)] #print '\nastart:<%r>' % attr_start # dbg if len(attr_start) < COMPLETE_THRESHOLD: attrs = list(set(attrs) - REMOTE_NAMES) # The base of the completion, so we can form the final results list bdot = base + '.' tcomp = [bdot + a for a in attrs] #print 'tcomp:',tcomp return tcomp
def trait_completer(self, event): """A custom IPython tab-completer that is traits-aware. It tries to hide the internal traits attributes, and reveal them only when it can reasonably guess that the user really is after one of them. """ # print '\nevent is:',event # dbg symbol_parts = event.symbol.split(".") base = ".".join(symbol_parts[:-1]) # print 'base:',base # dbg oinfo = self._ofind(base) if not oinfo["found"]: raise TryNext obj = oinfo["obj"] # OK, we got the object. See if it's traits, else punt if not isinstance(obj, T.HasTraits): raise TryNext # it's a traits object, don't show the tr* attributes unless the completion # begins with 'tr' attrs = dir2(obj) # Now, filter out the attributes that start with the user's request attr_start = symbol_parts[-1] if attr_start: attrs = [a for a in attrs if a.startswith(attr_start)] # Let's also respect the user's readline_omit__names setting: omit__names = ipget().options.readline_omit__names if omit__names == 1: attrs = [a for a in attrs if not a.startswith("__")] elif omit__names == 2: attrs = [a for a in attrs if not a.startswith("_")] # print '\nastart:<%r>' % attr_start # dbg if len(attr_start) < COMPLETE_THRESHOLD: attrs = list(set(attrs) - TRAIT_NAMES) # The base of the completion, so we can form the final results list bdot = base + "." tcomp = [bdot + a for a in attrs] # print 'tcomp:',tcomp return tcomp
def rep_completer(self, event, line=None): global _rep_res if line is None: line = readline.get_line_buffer() try: contextobj, attr = parseCommandLine(line, ipshell) if not isinstance(contextobj, representor.Representor): raise TryNext words = dir2(contextobj) if attr: words = [word for word in words if word.startswith(attr)] else: words = [word for word in words if not word.startswith("_")] _rep_res = (contextobj, attr, words) if attr: words = [event.symbol[: -len(attr)] + word for word in words] else: words = [event.symbol + word for word in words] return words except: raise TryNext
def _attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. This version is duct-taped into our QShell IPython instance. It is equal to the IPython 0.8.2 completer.py:Completer.attr_matches, except the end which adds a '(' to all callable attributes. """ import re import xmlrpclib try: from IPython.genutils import dir2 except ImportError: dir2 = dir # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if not m: return [] expr, attr = m.group(1, 3) try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] words = dir2(obj) # Build match list to return n = len(attr) #MOD from pylabs.extensions.PMExtensionsGroup import PMExtensionsGroup words2 = list() for word in words: classobj = obj if inspect.isclass(obj) else getattr(obj, '__class__', None) classattr = getattr(classobj, word, None) if classattr and type(classattr) == property: words2.append(word) elif isinstance(obj, PMExtensionsGroup): # We don't want a getattr() on PMExtensionGroups, since this call # would load the extension modules, which breaks our lazy loading # and makes everything just plain slow. Just append the 'word' # without any '(' since extensions are no callables anyway. # # This fixes DAL-2627 words2.append(word) else: try: iattr = getattr(obj, word) except Exception, e: words2.append(word) else: #Filter out enumeration stuff #If MyEnu is an enumeration, MyEnu.FOO.FOO should not be vissible #nor should MyEnu.FOO.registerItem #We want to filter out XMLRPC clients (getattr on them is not a good idea) if isinstance(iattr, xmlrpclib.Server): word = None elif getattr(iattr, '_pm_enumeration_hidden', False): if hasattr(obj, '_pm_enumeration_items') and inspect.isclass(obj): word = word elif not hasattr(obj, '_pm_enumeration_items') and not hasattr(obj, '_pm_enumeration_hidden'): #Item is attribute on 'something else' word = word else: word = None if word: words2.append("%s%s" % (word, "(" if (inspect.isfunction(iattr) or inspect.ismethod(iattr)) else ""))
set except: from sets import Set as set ############################################################################# # Module constants # The completion threshold # This is currently implemented as a module global, since this sytem isn't # likely to be modified at runtime by multiple instances. If needed in the # future, we can always make it local to the completer as a function attribute. COMPLETE_THRESHOLD = 3 # Set of names that Traits automatically adds to ANY traits-inheriting object. # These are the names we'll filter out. TRAIT_NAMES = set(dir2(T.HasTraits())) - set(dir2(object())) ############################################################################# # Code begins def trait_completer(self, event): """A custom IPython tab-completer that is traits-aware. It tries to hide the internal traits attributes, and reveal them only when it can reasonably guess that the user really is after one of them. """ # print '\nevent is:',event # dbg symbol_parts = event.symbol.split(".") base = ".".join(symbol_parts[:-1])
def _attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. This version is duct-taped into our QShell IPython instance. It is equal to the IPython 0.8.2 completer.py:Completer.attr_matches, except the end which adds a '(' to all callable attributes. """ import re import xmlrpclib try: from IPython.genutils import dir2 except ImportError: dir2 = dir # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if not m: return [] expr, attr = m.group(1, 3) try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] words = dir2(obj) # Build match list to return n = len(attr) #MOD from pylabs.extensions.PMExtensionsGroup import PMExtensionsGroup words2 = list() for word in words: classobj = obj if inspect.isclass(obj) else getattr( obj, '__class__', None) classattr = getattr(classobj, word, None) if classattr and type(classattr) == property: words2.append(word) elif isinstance(obj, PMExtensionsGroup): # We don't want a getattr() on PMExtensionGroups, since this call # would load the extension modules, which breaks our lazy loading # and makes everything just plain slow. Just append the 'word' # without any '(' since extensions are no callables anyway. # # This fixes DAL-2627 words2.append(word) else: try: iattr = getattr(obj, word) except Exception, e: words2.append(word) else: #Filter out enumeration stuff #If MyEnu is an enumeration, MyEnu.FOO.FOO should not be vissible #nor should MyEnu.FOO.registerItem #We want to filter out XMLRPC clients (getattr on them is not a good idea) if isinstance(iattr, xmlrpclib.Server): word = None elif getattr(iattr, '_pm_enumeration_hidden', False): if hasattr( obj, '_pm_enumeration_items') and inspect.isclass(obj): word = word elif not hasattr(obj, '_pm_enumeration_items') and not hasattr( obj, '_pm_enumeration_hidden'): #Item is attribute on 'something else' word = word else: word = None if word: words2.append("%s%s" % (word, "(" if (inspect.isfunction(iattr) or inspect.ismethod(iattr)) else ""))
set except: from sets import Set as set ############################################################################# # Module constants # The completion threshold # This is currently implemented as a module global, since this sytem isn't # likely to be modified at runtime by multiple instances. If needed in the # future, we can always make it local to the completer as a function attribute. COMPLETE_THRESHOLD = 3 # Set of names that Traits automatically adds to ANY traits-inheriting object. # These are the names we'll filter out. TRAIT_NAMES = set(dir2(T.HasTraits())) - set(dir2(object())) ############################################################################# # Code begins def trait_completer(self, event): """A custom IPython tab-completer that is traits-aware. It tries to hide the internal traits attributes, and reveal them only when it can reasonably guess that the user really is after one of them. """ #print '\nevent is:',event # dbg symbol_parts = event.symbol.split('.') base = '.'.join(symbol_parts[:-1])