Commit 152b3c21 authored by Kurt B. Kaiser's avatar Kurt B. Kaiser

Use inspect.py and clean up.

parent f40080f2
...@@ -8,6 +8,7 @@ which disappear when you type a closing parenthesis. ...@@ -8,6 +8,7 @@ which disappear when you type a closing parenthesis.
import re import re
import sys import sys
import types import types
import inspect
from idlelib import CallTipWindow from idlelib import CallTipWindow
from idlelib.HyperParser import HyperParser from idlelib.HyperParser import HyperParser
...@@ -25,42 +26,37 @@ class CallTips: ...@@ -25,42 +26,37 @@ class CallTips:
def __init__(self, editwin=None): def __init__(self, editwin=None):
if editwin is None: # subprocess and test if editwin is None: # subprocess and test
self.editwin = None self.editwin = None
return else:
self.editwin = editwin self.editwin = editwin
self.text = editwin.text self.text = editwin.text
self.calltip = None self.active_calltip = None
self._make_calltip_window = self._make_tk_calltip_window self._calltip_window = self._make_tk_calltip_window
def close(self): def close(self):
self._make_calltip_window = None self._calltip_window = None
def _make_tk_calltip_window(self): def _make_tk_calltip_window(self):
# See __init__ for usage # See __init__ for usage
return CallTipWindow.CallTip(self.text) return CallTipWindow.CallTip(self.text)
def _remove_calltip_window(self, event=None): def _remove_calltip_window(self, event=None):
if self.calltip: if self.active_calltip:
self.calltip.hidetip() self.active_calltip.hidetip()
self.calltip = None self.active_calltip = None
def force_open_calltip_event(self, event): def force_open_calltip_event(self, event):
"""Happens when the user really wants to open a CallTip, even if a "The user selected the menu entry or hotkey, open the tip."
function call is needed.
"""
self.open_calltip(True) self.open_calltip(True)
def try_open_calltip_event(self, event): def try_open_calltip_event(self, event):
"""Happens when it would be nice to open a CallTip, but not really """Happens when it would be nice to open a CallTip, but not really
neccesary, for example after an opening bracket, so function calls necessary, for example after an opening bracket, so function calls
won't be made. won't be made.
""" """
self.open_calltip(False) self.open_calltip(False)
def refresh_calltip_event(self, event): def refresh_calltip_event(self, event):
"""If there is already a calltip window, check if it is still needed, if self.active_calltip and self.active_calltip.is_active():
and if so, reload it.
"""
if self.calltip and self.calltip.is_active():
self.open_calltip(False) self.open_calltip(False)
def open_calltip(self, evalfuncs): def open_calltip(self, evalfuncs):
...@@ -72,20 +68,22 @@ class CallTips: ...@@ -72,20 +68,22 @@ class CallTips:
return return
hp.set_index(sur_paren[0]) hp.set_index(sur_paren[0])
name = hp.get_expression() name = hp.get_expression()
if not name or (not evalfuncs and name.find('(') != -1): if not name:
return
if not evalfuncs and (name.find('(') != -1):
return return
arg_text = self.fetch_tip(name) argspec = self.fetch_tip(name)
if not arg_text: if not argspec:
return return
self.calltip = self._make_calltip_window() self.active_calltip = self._calltip_window()
self.calltip.showtip(arg_text, sur_paren[0], sur_paren[1]) self.active_calltip.showtip(argspec, sur_paren[0], sur_paren[1])
def fetch_tip(self, name): def fetch_tip(self, name):
"""Return the argument list and docstring of a function or class """Return the argument list and docstring of a function or class.
If there is a Python subprocess, get the calltip there. Otherwise, If there is a Python subprocess, get the calltip there. Otherwise,
either fetch_tip() is running in the subprocess itself or it was called either this fetch_tip() is running in the subprocess or it was
in an IDLE EditorWindow before any script had been run. called in an IDLE running without the subprocess.
The subprocess environment is that of the most recently run script. If The subprocess environment is that of the most recently run script. If
two unrelated modules are being edited some calltips in the current two unrelated modules are being edited some calltips in the current
...@@ -103,10 +101,10 @@ class CallTips: ...@@ -103,10 +101,10 @@ class CallTips:
(name,), {}) (name,), {})
else: else:
entity = self.get_entity(name) entity = self.get_entity(name)
return get_arg_text(entity) return get_argspec(entity)
def get_entity(self, name): def get_entity(self, name):
"Lookup name in a namespace spanning sys.modules and __main.dict__" "Lookup name in a namespace spanning sys.modules and __main.dict__."
if name: if name:
namespace = sys.modules.copy() namespace = sys.modules.copy()
namespace.update(__main__.__dict__) namespace.update(__main__.__dict__)
...@@ -116,83 +114,66 @@ class CallTips: ...@@ -116,83 +114,66 @@ class CallTips:
return None return None
def _find_constructor(class_ob): def _find_constructor(class_ob):
# Given a class object, return a function object used for the "Find the nearest __init__() in the class tree."
# constructor (ie, __init__() ) or None if we can't find one.
try: try:
return class_ob.__init__.im_func return class_ob.__init__.im_func
except AttributeError: except AttributeError:
for base in class_ob.__bases__: for base in class_ob.__bases__:
rc = _find_constructor(base) init = _find_constructor(base)
if rc is not None: return rc if init:
return None return init
return None
def get_arg_text(ob):
"""Get a string describing the arguments for the given object""" def get_argspec(ob):
arg_text = "" """Get a string describing the arguments for the given object."""
argspec = ""
if ob is not None: if ob is not None:
arg_offset = 0
if isinstance(ob, type): if isinstance(ob, type):
# Look for the highest __init__ in the class chain.
fob = _find_constructor(ob) fob = _find_constructor(ob)
if fob is None: if fob is None:
fob = lambda: None fob = lambda: None
else:
arg_offset = 1
elif isinstance(ob, types.MethodType): elif isinstance(ob, types.MethodType):
# bit of a hack for methods - turn it into a function
# but we drop the "self" param.
fob = ob.im_func fob = ob.im_func
arg_offset = 1
else: else:
fob = ob fob = ob
# Try to build one for Python defined functions
if isinstance(fob, (types.FunctionType, types.LambdaType)): if isinstance(fob, (types.FunctionType, types.LambdaType)):
argcount = fob.__code__.co_argcount argspec = inspect.formatargspec(*inspect.getfullargspec(fob))
real_args = fob.__code__.co_varnames[arg_offset:argcount] pat = re.compile('self\,?\s*')
defaults = fob.__defaults__ or [] argspec = pat.sub("", argspec)
defaults = list(map(lambda name: "=%s" % repr(name), defaults))
defaults = [""] * (len(real_args) - len(defaults)) + defaults
items = list(map(lambda arg, dflt: arg + dflt, real_args, defaults))
if fob.__code__.co_flags & 0x4:
items.append("...")
if fob.__code__.co_flags & 0x8:
items.append("***")
arg_text = ", ".join(items)
arg_text = "(%s)" % re.sub("\.\d+", "<tuple>", arg_text)
# See if we can use the docstring
doc = getattr(ob, "__doc__", "") doc = getattr(ob, "__doc__", "")
if doc: if doc:
doc = doc.lstrip() doc = doc.lstrip()
pos = doc.find("\n") pos = doc.find("\n")
if pos < 0 or pos > 70: if pos < 0 or pos > 70:
pos = 70 pos = 70
if arg_text: if argspec:
arg_text += "\n" argspec += "\n"
arg_text += doc[:pos] argspec += doc[:pos]
return arg_text return argspec
################################################# #################################################
# #
# Test code # Test code
# #
if __name__=='__main__': def main():
def t1(): "()" def t1(): "()"
def t2(a, b=None): "(a, b=None)" def t2(a, b=None): "(a, b=None)"
def t3(a, *args): "(a, ...)" def t3(a, *args): "(a, *args)"
def t4(*args): "(...)" def t4(*args): "(*args)"
def t5(a, *args): "(a, ...)" def t5(a, *args): "(a, *args)"
def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)" def t6(a, b=None, *args, **kw): "(a, b=None, *args, **kw)"
class TC(object): class TC(object):
"(ai=None, ...)" "(ai=None, *b)"
def __init__(self, ai=None, *b): "(ai=None, ...)" def __init__(self, ai=None, *b): "(ai=None, *b)"
def t1(self): "()" def t1(self): "()"
def t2(self, ai, b=None): "(ai, b=None)" def t2(self, ai, b=None): "(ai, b=None)"
def t3(self, ai, *args): "(ai, ...)" def t3(self, ai, *args): "(ai, *args)"
def t4(self, *args): "(...)" def t4(self, *args): "(*args)"
def t5(self, ai, *args): "(ai, ...)" def t5(self, ai, *args): "(ai, *args)"
def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)" def t6(self, ai, b=None, *args, **kw): "(ai, b=None, *args, **kw)"
__main__.__dict__.update(locals())
def test(tests): def test(tests):
ct = CallTips() ct = CallTips()
...@@ -200,16 +181,16 @@ if __name__=='__main__': ...@@ -200,16 +181,16 @@ if __name__=='__main__':
for t in tests: for t in tests:
expected = t.__doc__ + "\n" + t.__doc__ expected = t.__doc__ + "\n" + t.__doc__
name = t.__name__ name = t.__name__
# exercise fetch_tip(), not just get_arg_text() # exercise fetch_tip(), not just get_argspec()
try: try:
qualified_name = "%s.%s" % (t.im_class.__name__, name) qualified_name = "%s.%s" % (t.im_class.__name__, name)
except AttributeError: except AttributeError:
qualified_name = name qualified_name = name
arg_text = ct.fetch_tip(qualified_name) argspec = ct.fetch_tip(qualified_name)
if arg_text != expected: if argspec != expected:
failed.append(t) failed.append(t)
fmt = "%s - expected %s, but got %s" fmt = "%s - expected %s, but got %s"
print(fmt % (t.__name__, expected, get_arg_text(t))) print(fmt % (t.__name__, expected, get_argspec(t)))
print("%d of %d tests failed" % (len(failed), len(tests))) print("%d of %d tests failed" % (len(failed), len(tests)))
tc = TC() tc = TC()
...@@ -217,3 +198,6 @@ if __name__=='__main__': ...@@ -217,3 +198,6 @@ if __name__=='__main__':
TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6) TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6)
test(tests) test(tests)
if __name__ == '__main__':
main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment