コード例 #1
0
    def test_ipy3_gh230(self):
        """https://github.com/IronLanguages/ironpython3/pull/230"""
        import inspect
        class test(object): pass

        self.assertFalse(inspect.ismethoddescriptor(test.__weakref__))
        self.assertFalse(inspect.ismethoddescriptor(test.__dict__["__dict__"]))
コード例 #2
0
ファイル: main.py プロジェクト: ahawker/scatter-gevent
    def func(self):
        import inspect
        print 'fuck'
        print inspect.ismethoddescriptor(self.__class__.x)
        for a in dir(self):
            v = getattr(self, a)
            print '{0} -- {1} -- {2}'.format(str(a), str(v), type(a))

        print type(self.x)
        print type(self.y)
コード例 #3
0
ファイル: main.py プロジェクト: ahawker/scatter-gevent
    def cfunc(cls):
        import inspect

        #for name, value in ((name, getattr(cls, name, None)) for name in dir(cls) if not name.startswith('_')):
        #    print ''


        print inspect.ismethoddescriptor(cls.x)
        for a in dir(cls):
            v = getattr(cls, a)
            print '{0} -- {1} -- {2}'.format(str(a), str(v), type(v))
コード例 #4
0
ファイル: whatis.py プロジェクト: melviso/python2-trepan
    def run(self, args):
        proc = self.proc
        arg = proc.cmd_argstr
        try:
            if not proc.curframe:
                # ?? Should we have set up a dummy globals
                # to have persistence?
                value = eval(arg, None, None)
            else:
                value = eval(arg, proc.curframe.f_globals,
                             proc.curframe.f_locals)
        except:
            t, v = sys.exc_info()[:2]
            if type(t) == str:
                exc_type_name = t
            else: exc_type_name = t.__name__
            if exc_type_name == 'NameError':
                self.errmsg("Name Error: %s" % arg)
            else:
                self.errmsg("%s: %s" % (exc_type_name, proc._saferepr(v)))
            return False

        self.section("What is for %s" % arg)

        get_doc = False
        if inspect.ismethod(value):
            get_doc = True
            self.msg('method %s%s' %
                     (value.func_code.co_name,
                       inspect.formatargspec(inspect.getargspec(value))))
        elif inspect.isfunction(value):
            get_doc = True
            self.msg('function %s%s' %
                     (value.func_code.co_name,
                       inspect.formatargspec(inspect.getargspec(value))))
        elif inspect.isabstract(value) or \
             inspect.isbuiltin(value) or \
             inspect.isclass(value) or \
             inspect.isgeneratorfunction(value) or \
             inspect.ismethoddescriptor(value):
            get_doc = True

        self.msg(type(value))
        doc = inspect.getdoc(value)
        if get_doc and doc:
            self.msg('  doc:\n%s' % doc)
        comments = inspect.getcomments(value)
        if comments:
            self.msg('  comments:\n%s' % comments)
        try:
            m = inspect.getmodule(value)
            if m: self.msg("  module:\t%s" % m)
        except:
            try:
                f = inspect.getfile(value)
                self.msg("  file: %s" % f)
            except:
                pass
            pass
        return False
コード例 #5
0
ファイル: epydoc.py プロジェクト: 007durgesh219/jessies
def PrintHtml(name, things):
  """Print HTML documentation to stdout."""
  ambiguous = len(things) > 1
  
  content = ""
  for thing in things:
    obj, name = pydoc.resolve(thing, forceload=0)
    title = pydoc.describe(obj)
    if ambiguous:
      if inspect.ismethoddescriptor(obj):
        content += '\n\n<h2>method %s in class %s</h2>\n' % (obj.__name__, obj.__dict__)
      else:
        content += '<h2>%s in module <a href="py:%s">%s</a></h2>\n' % (title, obj.__module__, obj.__module__)
    content += pydoc.html.document(obj, name)
  
  if ambiguous:
    title = 'Matches for "%s"' % name
    content = '<h1>%s</h1>\n\n%s' % (title, content)
  
  page = pydoc.html.page(title, content)
  
  # Note: rewriting the anchors in a form more useful to Evergreen should be in Evergreen, not here.
  # The rewriting here should be generally useful to anyone or anything that needs Python documentation.
  
  # Remove a couple of useless (and seemingly broken) links.
  page = page.replace('<a href=".">index</a><br>', '')
  page = re.sub('<br><a href="[^"]+\.html">Module Docs</a>', '', page)
  
  # There's a bug in pydoc that makes it output the text of the "Modules" section in cyan instead of white.
  page = re.sub('"#fffff"', '"#ffffff"', page)
  # The explicit font specifications are unnecessary manual uglification.
  page = re.sub(' face="[^"]+"', '', page);
  
  sys.stdout.write(page + '\n')
コード例 #6
0
ファイル: VideoPlayer.py プロジェクト: Swizec/IJS-stuff
def return_feasible_playback_modes(syspath):
    l = []
    try:
        import vlc

        if USE_VLC_RAW_INTERFACE:
            # check if the special raw interface is available
            # pylint: disable-msg=E1101
            if not inspect.ismethoddescriptor(vlc.MediaControl.set_raw_callbacks):
                raise Exception("Incorrect vlc plugin. This does not provide the set_raw_callbacks method")
            # pylint: enable-msg=E1101
        vlcpath = os.path.join(syspath,"vlc")
        if sys.platform == 'win32':
            if os.path.isdir(vlcpath):
                l.append(PLAYBACKMODE_INTERNAL)
        else:
            l.append(PLAYBACKMODE_INTERNAL)
    except Exception:
        print_exc()
    
    if sys.platform == 'win32':
        l.append(PLAYBACKMODE_EXTERNAL_MIME)
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
    else:
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
    return l
コード例 #7
0
ファイル: inspection.py プロジェクト: hirochachacha/apython
def getargspec(func, f):
    # Check if it's a real bound method or if it's implicitly calling __init__
    # (i.e. FooClass(...) and not FooClass.__init__(...) -- the former would
    # not take 'self', the latter would:
    try:
        func_name = getattr(f, '__name__', None)
    except TypeError:
        return None

    try:
        is_bound_method = ((inspect.ismethod(f) and f.im_self is not None)
                           or (func_name == '__init__' and not
        func.endswith('.__init__')))
    except:
        # if f is a method from a xmlrpclib.Server instance, func_name ==
        # '__init__' throws xmlrpclib.Fault (see #202)
        return None
    try:
        if PY3:
            argspec = inspect.getfullargspec(f)
        else:
            argspec = inspect.getargspec(f)

        argspec = list(argspec)
        fixlongargs(f, argspec)
        argspec = [func, argspec, is_bound_method]
    except (TypeError, KeyError):
        with AttrCleaner(f):
            argspec = getpydocspec(f, func)
        if argspec is None:
            return None
        if inspect.ismethoddescriptor(f):
            argspec[1][0].insert(0, 'obj')
        argspec.append(is_bound_method)
    return argspec
コード例 #8
0
ファイル: base.py プロジェクト: Kortemme-Lab/kddg
    def getMembers(cls):

        lfunctions = []
        lmethods = []
        lattributes = []
        for m in inspect.getmembers(cls):
            m_name = m[0]
            m_object = m[1]
            if cls.__dict__.get(m_name):
                # Do not print inherited names
                #print(type(m_object))
                if m_name[0] != "_" and m_name not in kobject.ignore_list:
                    if inspect.isbuiltin(m_object):
                        pass
                    elif inspect.iscode(m_object):
                        pass
                    elif inspect.ismodule(m_object):
                        pass
                    elif inspect.ismethoddescriptor(m_object):
                        pass
                    elif inspect.isdatadescriptor(m_object):
                        pass
                    elif inspect.ismethod(m_object):
                        lmethods.append(m)
                    elif inspect.isfunction(m_object):
                        lfunctions.append(m)
                    elif inspect.isroutine(m_object):
                        pass
                    else:
                        lattributes.append(m)

        return {"functions" : lfunctions, "methods" : lmethods, "attributes" : lattributes}
コード例 #9
0
ファイル: builtin.py プロジェクト: kpanic/dotvim-python-ide
 def get_scope_objects(names):
     """
     Looks for the names defined with dir() in an objects and divides
     them into different object types.
     """
     classes = {}
     funcs = {}
     stmts = {}
     members = {}
     for n in names:
         if '__' in n and n not in mixin_funcs:
             continue
         try:
             # this has a builtin_function_or_method
             exe = getattr(scope, n)
         except AttributeError:
             # happens e.g. in properties of
             # PyQt4.QtGui.QStyleOptionComboBox.currentText
             # -> just set it to None
             members[n] = None
         else:
             if inspect.isclass(scope):
                 if is_in_base_classes(scope, n, exe):
                     continue
             if inspect.isbuiltin(exe) or inspect.ismethod(exe) \
                         or inspect.ismethoddescriptor(exe):
                 funcs[n] = exe
             elif inspect.isclass(exe):
                 classes[n] = exe
             elif inspect.ismemberdescriptor(exe):
                 members[n] = exe
             else:
                 stmts[n] = exe
     return classes, funcs, stmts, members
コード例 #10
0
ファイル: utils.py プロジェクト: Jaykul/beakerx
 def default(self, obj):
   if isinstance(obj, datetime):
     return self.default(date_time_2_millis(obj))
   elif isinstance(obj, Enum):
     return self.default(obj.name)
   elif isinstance(obj, Color):
     return self.default(obj.hex())
   elif hasattr(obj, "__dict__"):
     d = dict(
       (key, value)
       for key, value in inspect.getmembers(obj)
       if value is not None
       and not key == "Position"
       and not key.startswith("__")
       and not inspect.isabstract(value)
       and not inspect.isbuiltin(value)
       and not inspect.isfunction(value)
       and not inspect.isgenerator(value)
       and not inspect.isgeneratorfunction(value)
       and not inspect.ismethod(value)
       and not inspect.ismethoddescriptor(value)
       and not inspect.isroutine(value)
     )
     return self.default(d)
   return obj
コード例 #11
0
 def attrfilter(attr):
     # Only add methods and attributes of the class to the CIX.
     # - "os._Environ" seems to be a particular problem case in that
     #   some methods defined on it are inspect.ismethod() but not
     #   inspect.ismethoddescriptor(). Not so for other examples in
     #   modules that stdcix.py processes, and adding .ismethod() to this
     #   filter adds unwanted methods on C-defined module exception
     #   classes.
     if not (inspect.isdatadescriptor(attr)
             or inspect.ismethoddescriptor(attr)
             or inspect.ismethod(attr) or
             inspect.isfunction(attr)):
         return False
     # Skip inherited attributes in the CIX.
     try:
         attrname = attr.__name__
         for base in obj.__bases__:
             if hasattr(base, attrname) and getattr(base, attrname) is \
                 getattr(obj, attrname):
                 return False
     except AttributeError:
         # staticmethod and classmethod objects don't have a __name__
         pass
         #print "Couldn't process: %r, assuming ok" % str(attr)
     return True
コード例 #12
0
ファイル: hook.py プロジェクト: TanayGahlot/PySyft
    def _hook_variable(self):
        """Responsible for hooking Variable methods"""
        # Overload 'special' methods here
        self._hook___new__(torch.autograd.variable.Variable)
        self._hook_var_contents()
        self._hook_var_owners()

        for attr in dir(torch.autograd.variable.Variable):

            # Conditions for inclusion/exclusion
            if attr in self.exclude + self.var_exclude:
                continue
            lit = getattr(torch.autograd.variable.Variable, attr)
            is_base = attr in dir(object)
            is_desc = inspect.ismethoddescriptor(lit)
            # is_func = isinstance(type(lit), types.FunctionType)
            is_func = isinstance(lit, types.FunctionType)
            try:
                is_service_func = 'HookService' in lit.__qualname__
            except:
                is_service_func = False
            is_old = re.match('old*', attr) is not None

            # Where the overloading happens
            if ((is_desc or (is_func and not is_service_func)) and not is_base and not is_old):
                passer = utils.pass_method_args(lit)
                new_attr = self._get_overload_method_in_tensor_or_var(passer)
                setattr(torch.autograd.variable.Variable,
                        'old_{}'.format(attr), lit)
                setattr(torch.autograd.variable.Variable, attr, new_attr)

        self._hook_send_(torch.autograd.variable.Variable)
        self._hook_get_(torch.autograd.variable.Variable)
        self._hook_var_serde()
コード例 #13
0
ファイル: hook.py プロジェクト: TanayGahlot/PySyft
    def _hook_tensor(self, tensor_type):
        """Overloading a given tensor_type"""
        # Overload 'special' methods here
        self._hook___new__(tensor_type)
        self._hook_tensor___repr__(tensor_type)
        self._hook_fixed_precision_methods(tensor_type)

        for attr in dir(tensor_type):
            # if we haven't already overloaded this function
            if 'old_{}'.format(attr) not in dir(tensor_type):
                # Conditions for inclusion/exclusion
                if attr in self.exclude:
                    continue
                lit = getattr(tensor_type, attr)
                is_base = attr in dir(object)
                is_desc = inspect.ismethoddescriptor(lit)
                is_func = isinstance(lit, types.FunctionType)
                try:
                    is_service_func = 'HookService' in lit.__qualname__
                except:
                    is_service_func = False
                is_old = re.match('old*', attr) is not None

                # Where the overloading happens
                if ((is_desc or (is_func and not is_service_func)) and not is_base and not is_old):
                    passer = utils.pass_method_args(lit)
                    new_attr = self._get_overload_method_in_tensor_or_var(passer)
                    setattr(tensor_type, 'old_{}'.format(attr), lit)
                    setattr(tensor_type, attr, new_attr)

        # Add in our own Grid-specific methods
        self._hook_send_(tensor_type)
        self._hook_get_(tensor_type)
        self._hook_tensor__serde(tensor_type)
コード例 #14
0
ファイル: builtins.py プロジェクト: Ampersandy/python-mode
def _object_attributes(obj, parent):
    attributes = {}
    for name in dir(obj):
        if name == 'None':
            continue
        try:
            child = getattr(obj, name)
        except AttributeError:
            # descriptors are allowed to raise AttributeError
            # even if they are in dir()
            continue
        pyobject = None
        if inspect.isclass(child):
            pyobject = BuiltinClass(child, {}, parent=parent)
        elif inspect.isroutine(child):
            if inspect.ismethoddescriptor(child) and "__weakref__" in dir(obj):
                try:
                    weak = child.__get__(obj.__weakref__.__objclass__())
                except:
                    weak = child
                pyobject = BuiltinFunction(builtin=weak, parent=parent)
            else:
                pyobject = BuiltinFunction(builtin=child, parent=parent)
        else:
            pyobject = BuiltinUnknown(builtin=child)
        attributes[name] = BuiltinName(pyobject)
    return attributes
コード例 #15
0
ファイル: _types.py プロジェクト: gitter-badger/cinspect
def get_cinspect_object(obj):
    """ Returns the object wrapped in the appropriate CInspectObject class. """

    try:
        igetsource(obj)
    except (TypeError, IOError) as e:
        # The code to deal with this case is below
        pass
    else:
        return PythonObject(obj)

    if inspect.isbuiltin(obj):
        if obj.__module__ is None:
            # fixme: we could possibly check in `types` to see if it's really a
            # built-in...
            return BuiltinMethod(obj)
        else:
            # Any builtin/compiled functions ...
            return BuiltinFunction(obj)

    elif inspect.ismethoddescriptor(obj):
        return MethodDescriptor(obj)

    elif inspect.ismodule(obj):
        return Module(obj)

    elif inspect.isclass(obj):
        return Type(obj)

    elif inspect.isclass(type(obj)):
        return Type(obj.__class__)

    else:
        raise NotImplementedError
コード例 #16
0
ファイル: VideoPlayer.py プロジェクト: egbertbouman/tribler-g
def return_feasible_playback_modes(syspath):
    l = []
    try:
        if sys.platform == "darwin":
            oldpath = os.getcwd()
            os.chdir(os.path.join(syspath,'vlc','lib'))
            import vlc.lib.vlc as vlc
            os.chdir(oldpath)
        else:
            import Tribler.vlc as vlc

        if USE_VLC_RAW_INTERFACE:
            # check if the special raw interface is available
            # pylint: disable-msg=E1101
            if not inspect.ismethoddescriptor(vlc.MediaControl.set_raw_callbacks):
                raise Exception("Incorrect vlc plugin. This does not provide the set_raw_callbacks method")
            # pylint: enable-msg=E1101
        l.append(PLAYBACKMODE_INTERNAL)
# boudewijn: 06/06/2011: if import vlc was ok, then we can also find the vlc dll/so
#        vlcpath = os.path.join(syspath,"vlc")
#        if sys.platform == 'win32':
#            
#            if os.path.isdir(vlcpath):
#                l.append(PLAYBACKMODE_INTERNAL)
#        else:
#            l.append(PLAYBACKMODE_INTERNAL)
    except Exception:
        print_exc()
    
    if sys.platform == 'win32':
        l.append(PLAYBACKMODE_EXTERNAL_MIME)
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
    else:
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
    return l
コード例 #17
0
 def print_variable_type(self, objType):
     default_vars=["__builtins__", "__doc__","__path__", "__cached__", "__file__", "__name__", "__package__", "__version__"]
     self.dprint("[ %s ]" %objType.__name__)
     self.indent();self.indent()
     for ModObj in self.Modules:
         for name in dir(ModObj):
             obj = getattr(ModObj, name)
             #print(name, ":", type(obj))
             if not (inspect.isclass(obj) or
                 inspect.isfunction(obj)  or
                 inspect.isroutine(obj)  or
                 inspect.isfunction(obj)  or
                 inspect.isgeneratorfunction(obj)  or
                 inspect.isgenerator(obj)  or
                 inspect.istraceback(obj)  or
                 inspect.isframe(obj)      or
                 inspect.iscode(obj)       or
                 inspect.isabstract(obj)   or
                 inspect.ismethoddescriptor(obj)  or
                 inspect.isdatadescriptor(obj)    or
                 inspect.isgetsetdescriptor(obj)  or
                 inspect.ismemberdescriptor(obj)  or
                 inspect.isbuiltin(obj)):
                 if name not in default_vars:
                     if type(obj) is  objType:
                         ObjName = ModObj.__name__ + '.' + name
                         self.dprint("%s" %ObjName)
     self.dedent();self.dedent()
コード例 #18
0
ファイル: class_.py プロジェクト: wpjunior/proled
 def getAttributes(self):
     """See IClassDocumentation."""
     return [
         (name, obj, iface)
         for name, obj, iface in self._iterAllAttributes()
         if not (ismethod(obj) or ismethoddescriptor(obj))
     ]
コード例 #19
0
ファイル: introspector.py プロジェクト: wpjunior/proled
    def getAttributes(self):
        # remove the security proxy, so that `attr` is not proxied. We could
        # unproxy `attr` for each turn, but that would be less efficient.
        #
        # `getPermissionIds()` also expects the class's security checker not
        # to be proxied.
        klass = zope.security.proxy.removeSecurityProxy(self.klassView.context)
        obj = zope.security.proxy.removeSecurityProxy(self.context)

        for name in apidoc.utilities.getPublicAttributes(obj):
            value = getattr(obj, name)
            if inspect.ismethod(value) or inspect.ismethoddescriptor(value):
                continue
            entry = {
                'name': name,
                'value': `value`,
                'value_linkable': IPhysicallyLocatable(value, False) and True,
                'type': type(value).__name__,
                'type_link': getTypeLink(type(value)),
                'interface': apidoc.utilities.getInterfaceForAttribute(
                                 name, klass._Class__all_ifaces)
                }
            entry.update(apidoc.utilities.getPermissionIds(
                name, klass.getSecurityChecker()))
            yield entry
コード例 #20
0
ファイル: inspect.py プロジェクト: papadeltasierra/sphinx
    def _finddoc(obj):
        # type: (Any) -> unicode
        if inspect.isclass(obj):
            for base in obj.__mro__:
                if base is not object:
                    try:
                        doc = base.__doc__
                    except AttributeError:
                        continue
                    if doc is not None:
                        return doc
            return None

        if inspect.ismethod(obj) and getattr(obj, '__self__', None):
            name = obj.__func__.__name__
            self = obj.__self__
            if (inspect.isclass(self) and
                    getattr(getattr(self, name, None), '__func__')
                    is obj.__func__):
                # classmethod
                cls = self
            else:
                cls = self.__class__
        elif inspect.isfunction(obj) or inspect.ismethod(obj):
            name = obj.__name__
            cls = _findclass(obj)
            if cls is None or getattr(cls, name) != obj:
                return None
        elif inspect.isbuiltin(obj):
            name = obj.__name__
            self = obj.__self__
            if (inspect.isclass(self) and
                    self.__qualname__ + '.' + name == obj.__qualname__):
                # classmethod
                cls = self
            else:
                cls = self.__class__
        # Should be tested before isdatadescriptor().
        elif isinstance(obj, property):
            func = obj.fget
            name = func.__name__
            cls = _findclass(func)
            if cls is None or getattr(cls, name) is not obj:
                return None
        elif inspect.ismethoddescriptor(obj) or inspect.isdatadescriptor(obj):
            name = obj.__name__
            cls = obj.__objclass__
            if getattr(cls, name) is not obj:
                return None
        else:
            return None

        for base in cls.__mro__:
            try:
                doc = getattr(base, name).__doc__
            except AttributeError:
                continue
            if doc is not None:
                return doc
        return None
コード例 #21
0
ファイル: __init__.py プロジェクト: ColossusPenguin/.emacs.d
    def get_param_names(self):
        obj = self.obj
        try:
            if py_version < 33:
                raise ValueError("inspect.signature was introduced in 3.3")
            if py_version == 34:
                # In 3.4 inspect.signature are wrong for str and int. This has
                # been fixed in 3.5. The signature of object is returned,
                # because no signature was found for str. Here we imitate 3.5
                # logic and just ignore the signature if the magic methods
                # don't match object.
                # 3.3 doesn't even have the logic and returns nothing for str
                # and classes that inherit from object.
                user_def = inspect._signature_get_user_defined_method
                if (inspect.isclass(obj)
                        and not user_def(type(obj), '__init__')
                        and not user_def(type(obj), '__new__')
                        and (obj.__init__ != object.__init__
                             or obj.__new__ != object.__new__)):
                    raise ValueError

            signature = inspect.signature(obj)
        except ValueError:  # Has no signature
            params_str, ret = self._parse_function_doc()
            tokens = params_str.split(',')
            if inspect.ismethoddescriptor(obj):
                tokens.insert(0, 'self')
            for p in tokens:
                parts = p.strip().split('=')
                yield UnresolvableParamName(self, parts[0])
        else:
            for signature_param in signature.parameters.values():
                yield SignatureParamName(self, signature_param)
コード例 #22
0
ファイル: currying.py プロジェクト: vapier/snakeoil
def _inspect_isroutine_override(object):
    import inspect
    return (isinstance(object, partial)
            or inspect.isbuiltin(object)
            or inspect.isfunction(object)
            or inspect.ismethod(object)
            or inspect.ismethoddescriptor(object))
コード例 #23
0
    def getAttributes(self):
        # remove the security proxy, so that `attr` is not proxied. We could
        # unproxy `attr` for each turn, but that would be less efficient.
        #
        # `getPermissionIds()` also expects the class's security checker not
        # to be proxied.
        klass = zope.security.proxy.removeSecurityProxy(self.klassView.context)
        obj = zope.security.proxy.removeSecurityProxy(self.context)

        for name in apidoc.utilities.getPublicAttributes(obj):
            value = getattr(obj, name)
            if inspect.ismethod(value) or inspect.ismethoddescriptor(value):
                # Because getPublicAttributes(obj) loops through
                # dir(obj) which is more or less obj.__dict__, and
                # when obj is an instance (and not a class), its
                # __dict__ tends not to have methods in it, so this condition
                # should typically not be taken.
                continue  # pragma: no cover
            entry = {
                'name': name,
                'value': repr(value),
                'value_linkable': IPhysicallyLocatable(value, False) and True,
                'type': type(value).__name__,
                'type_link': getTypeLink(type(value)),
                'interface': apidoc.utilities.getInterfaceForAttribute(
                    name, klass._Class__all_ifaces)
                }
            entry.update(apidoc.utilities.getPermissionIds(
                name, klass.getSecurityChecker()))
            yield entry
コード例 #24
0
 def should_be_checked( self, obj, module=None ):
     """returns True, if obj should be checked, False otherwise"""
     if id(obj) in self.__checked:
         return False
     if inspect.isbuiltin( obj ):
         return False
     if inspect.ismodule( obj ):
         if obj.__name__ in self.__already_imported:
             return False #do not check already imported modules
         source_file = self.getsourcefile(obj)
         if source_file:
             return contains_parent_dir( source_file, self.__include_paths )
         else:
             return False
     obj_module = inspect.getmodule( obj )
     if not obj_module is module:
         return False
     if inspect.isclass( obj ) \
        or inspect.ismethod( obj ) \
        or inspect.isfunction( obj ) \
        or inspect.isroutine( obj ) \
        or inspect.ismethoddescriptor( obj ) \
        or inspect.isdatadescriptor( obj ):
         return True
     return False
コード例 #25
0
    def getMethods(self):
        # remove the security proxy, so that `attr` is not proxied. We could
        # unproxy `attr` for each turn, but that would be less efficient.
        #
        # `getPermissionIds()` also expects the class's security checker not
        # to be proxied.
        klass = zope.security.proxy.removeSecurityProxy(self.klassView.context)
        obj = zope.security.proxy.removeSecurityProxy(self.context)

        for name in apidoc.utilities.getPublicAttributes(obj):
            val = getattr(obj, name)
            if not (inspect.ismethod(val) or inspect.ismethoddescriptor(val)):
                continue

            signature = apidoc.utilities.getFunctionSignature(val)

            entry = {
                'name': name,
                'signature': signature,
                'doc': apidoc.utilities.renderText(
                    val.__doc__ or '',
                    getParent(self.klassView.context).getPath()),
                'interface': apidoc.utilities.getInterfaceForAttribute(
                    name, klass._Class__all_ifaces)}

            entry.update(apidoc.utilities.getPermissionIds(
                name, klass.getSecurityChecker()))

            yield entry
コード例 #26
0
ファイル: python.py プロジェクト: WesleyFrancisco/scrapy
def get_func_args(func, stripself=False):
    """Return the argument name list of a callable"""
    if inspect.isfunction(func):
        func_args, _, _, _ = inspect.getargspec(func)
    elif inspect.isclass(func):
        return get_func_args(func.__init__, True)
    elif inspect.ismethod(func):
        return get_func_args(func.__func__, True)
    elif inspect.ismethoddescriptor(func):
        return []
    elif isinstance(func, partial):
        return [x for x in get_func_args(func.func)[len(func.args):]
                if not (func.keywords and x in func.keywords)]
    elif hasattr(func, '__call__'):
        if inspect.isroutine(func):
            return []
        elif getattr(func, '__name__', None) == '__call__':
            return []
        else:
            return get_func_args(func.__call__, True)
    else:
        raise TypeError('%s is not callable' % type(func))
    if stripself:
        func_args.pop(0)
    return func_args
コード例 #27
0
ファイル: ipdoctest.py プロジェクト: 0038lana/Test-Task
 def _from_module(self, module, object):
     """
     Return true if the given object is defined in the given
     module.
     """
     if module is None:
         return True
     elif inspect.isfunction(object):
         return module.__dict__ is object.__globals__
     elif inspect.isbuiltin(object):
         return module.__name__ == object.__module__
     elif inspect.isclass(object):
         return module.__name__ == object.__module__
     elif inspect.ismethod(object):
         # This one may be a bug in cython that fails to correctly set the
         # __module__ attribute of methods, but since the same error is easy
         # to make by extension code writers, having this safety in place
         # isn't such a bad idea
         return module.__name__ == object.__self__.__class__.__module__
     elif inspect.getmodule(object) is not None:
         return module is inspect.getmodule(object)
     elif hasattr(object, '__module__'):
         return module.__name__ == object.__module__
     elif isinstance(object, property):
         return True # [XX] no way not be sure.
     elif inspect.ismethoddescriptor(object):
         # Unbound PyQt signals reach this point in Python 3.4b3, and we want
         # to avoid throwing an error. See also http://bugs.python.org/issue3158
         return False
     else:
         raise ValueError("object must be a class or function, got %r" % object)
コード例 #28
0
def describe_module(module, kind, constants=[]):
    """
    Describe the module object passed as argument
    including its classes and functions.
    """

    module_name = module.__name__

    if kind == object_types.LIBRARY:
        klass = Library(module_name)
    else:
        klass = Module(module_name, kind)
        
    klass.docs = getdoc(module)
    klass.comments = getcomments(module)
    
    klass.filename = module.__file__
    inheritance_diagram = []
    
    count = 0
   
    for name in dir(module):
        
        if name in EXCLUDED_ATTRS:
            continue
        
        obj = getattr(module, name)

        if ismodule(obj):
            continue

        if ismemberdescriptor(obj) or isgetsetdescriptor(obj):
            continue
        
        if isclass(obj):
            count += 1
            describe_class(obj, klass, module_name, constants)

            if obj.__module__ == module.__name__:
                inheritance_diagram.append(obj)
            
        elif isbuiltin(obj):
            count += 1
        elif ismethod(obj) or isfunction(obj) or ismethoddescriptor(obj) or \
             isinstance(obj, types.MethodType):
            count +=1
            describe_func(obj, klass, module_name)
        else:
            attribute = Attribute(module_name + '.' + name, type(obj), obj)
            klass.Add(attribute)

            if constants:
                attribute.is_redundant = name not in constants

    if kind not in [object_types.PACKAGE, object_types.LIBRARY]:
        if inheritance_diagram and len(inheritance_diagram) < 20:
            klass.inheritance_diagram = inheritance.InheritanceDiagram(inheritance_diagram, klass)

    return klass, count
コード例 #29
0
ファイル: inspect_c4d.py プロジェクト: seeminglee/c4d
def write_class(module, classname, classvalue):

    classes = []
    methods = []
    builtins = []
    functions = []
    methoddescs = []
    others = []

    theclass = '{0}.{1}'.format(module.__name__, classname)
    theclass = eval(theclass)

    for name, value in inspect.getmembers(theclass):
        if not isprivateobj(name):
            if inspect.isclass(value):
                classes.append((name, value))
            elif inspect.ismethod(value):
                methods.append((name, value))
            elif inspect.isfunction(value):
                functions.append((name, value))
            elif inspect.isbuiltin(value):
                builtins.append((name, value))
            elif inspect.ismethoddescriptor(value):
                methoddescs.append((name, value))
            else:
                others.append((name, value))

    if not others:
        members = [fmt_class_nomembers]
    else:
        members = [fmt_class_member.format(name=n, value=v) for n, v in others]

    s_classes = [fmt_class_class.format(classname=name, docstring=value.__doc__) \
                 for name, value in classes]

    s_methods = [fmt_class_method.format(methodname=name, docstring=value.__doc__) \
                 for name, value in (methods + functions + builtins + methoddescs)]

    out = fmt_class.format(
        modulename = module.__name__,
        classname = classname,
        docstring = theclass.__doc__,
        members = '\n'.join(members),
        classes = '\n'.join(s_classes),
        methods = '\n'.join(s_methods)                     
    )

    mpath = modulepath(module)
    if not os.path.exists(mpath):
        os.makedirs(mpath)
    cfile = os.path.join(mpath, classname + '.py')

    try:
        with open(cfile, 'w') as f:
            f.write(out)
            f.close()
            print(cfile)
    except IOError:
        print "IOError"
コード例 #30
0
ファイル: __init__.py プロジェクト: fastmonkeys/jedi
 def get_param_names(self):
     params_str, ret = self._parse_function_doc()
     tokens = params_str.split(',')
     if inspect.ismethoddescriptor(self.obj):
         tokens.insert(0, 'self')
     for p in tokens:
         parts = p.strip().split('=')
         yield UnresolvableParamName(self, parts[0])