def _get_jy_dictionary(self, obj):
        ret = {}
        found = java.util.HashMap()

        original = obj
        if hasattr_checked(obj,
                           '__class__') and obj.__class__ == java.lang.Class:

            # get info about superclasses
            classes = []
            classes.append(obj)
            c = obj.getSuperclass()
            while c != None:
                classes.append(c)
                c = c.getSuperclass()

            # get info about interfaces
            interfs = []
            for obj in classes:
                interfs.extend(obj.getInterfaces())
            classes.extend(interfs)

            # now is the time when we actually get info on the declared methods and fields
            for obj in classes:

                declaredMethods = obj.getDeclaredMethods()
                declaredFields = obj.getDeclaredFields()
                for i in xrange(len(declaredMethods)):
                    name = declaredMethods[i].getName()
                    ret[name] = declaredMethods[i].toString()
                    found.put(name, 1)

                for i in xrange(len(declaredFields)):
                    name = declaredFields[i].getName()
                    found.put(name, 1)
                    # if declaredFields[i].isAccessible():
                    declaredFields[i].setAccessible(True)
                    # ret[name] = declaredFields[i].get( declaredFields[i] )
                    try:
                        ret[name] = declaredFields[i].get(original)
                    except:
                        ret[name] = declaredFields[i].toString()

        # this simple dir does not always get all the info, that's why we have the part before
        # (e.g.: if we do a dir on String, some methods that are from other interfaces such as
        # charAt don't appear)
        try:
            d = dir(original)
            for name in d:
                if found.get(name) != 1:
                    ret[name] = getattr(original, name)
        except:
            # sometimes we're unable to do a dir
            pass

        return ret
 def get_names(self, var):
     used___dict__ = False
     try:
         names = dir(var)
     except Exception:
         names = []
     if not names:
         if hasattr_checked(var, '__dict__'):
             names = dict_keys(var.__dict__)
             used___dict__ = True
     return names, used___dict__
Exemple #3
0
def get_file(mod):
    f = None
    try:
        f = inspect.getsourcefile(mod) or inspect.getfile(mod)
    except:
        if hasattr_checked(mod, '__file__'):
            f = mod.__file__
            if f.lower(f[-4:]) in ['.pyc', '.pyo']:
                filename = f[:-4] + '.py'
                if os.path.exists(filename):
                    f = filename

    return f
Exemple #4
0
def get_variable_details(val, evaluate_full_value=True, to_string=None):
    try:
        # This should be faster than isinstance (but we have to protect against not having a '__class__' attribute).
        is_exception_on_eval = val.__class__ == ExceptionOnEvaluate
    except:
        is_exception_on_eval = False

    if is_exception_on_eval:
        v = val.result
    else:
        v = val

    _type, type_name, resolver = get_type(v)
    type_qualifier = getattr(_type, "__module__", "")
    if not evaluate_full_value:
        value = DEFAULT_VALUE
    else:
        try:
            str_from_provider = _str_from_providers(v, _type, type_name)
            if str_from_provider is not None:
                value = str_from_provider

            elif to_string is not None:
                value = to_string(v)

            elif hasattr_checked(v, '__class__'):
                if v.__class__ == frame_type:
                    value = pydevd_resolver.frameResolver.get_frame_name(v)

                elif v.__class__ in (list, tuple):
                    if len(v) > 300:
                        value = '%s: %s' % (str(
                            v.__class__), '<Too big to print. Len: %s>' %
                                            (len(v), ))
                    else:
                        value = '%s: %s' % (str(v.__class__), v)
                else:
                    try:
                        cName = str(v.__class__)
                        if cName.find('.') != -1:
                            cName = cName.split('.')[-1]

                        elif cName.find(
                                "'"
                        ) != -1:  # does not have '.' (could be something like <type 'int'>)
                            cName = cName[cName.index("'") + 1:]

                        if cName.endswith("'>"):
                            cName = cName[:-2]
                    except:
                        cName = str(v.__class__)

                    value = '%s: %s' % (cName, v)
            else:
                value = str(v)
        except:
            try:
                value = repr(v)
            except:
                value = 'Unable to get repr for %s' % v.__class__

    # fix to work with unicode values
    try:
        if not IS_PY3K:
            if value.__class__ == unicode:  # @UndefinedVariable
                value = value.encode('utf-8', 'replace')
        else:
            if value.__class__ == bytes:
                value = value.decode('utf-8', 'replace')
    except TypeError:
        pass

    return type_name, type_qualifier, is_exception_on_eval, resolver, value
def generate_imports_tip_for_module(obj_to_complete,
                                    dir_comps=None,
                                    getattr=getattr,
                                    filter=lambda name: True):
    '''
        @param obj_to_complete: the object from where we should get the completions
        @param dir_comps: if passed, we should not 'dir' the object and should just iterate those passed as kwonly_arg parameter
        @param getattr: the way to get kwonly_arg given object from the obj_to_complete (used for the completer)
        @param filter: kwonly_arg callable that receives the name and decides if it should be appended or not to the results
        @return: list of tuples, so that each tuple represents kwonly_arg completion with:
            name, doc, args, type (from the TYPE_* constants)
    '''
    ret = []

    if dir_comps is None:
        dir_comps = dir_checked(obj_to_complete)
        if hasattr_checked(obj_to_complete, '__dict__'):
            dir_comps.append('__dict__')
        if hasattr_checked(obj_to_complete, '__class__'):
            dir_comps.append('__class__')

    get_complete_info = True

    if len(dir_comps) > 1000:
        # ok, we don't want to let our users wait forever...
        # no complete info for you...

        get_complete_info = False

    dontGetDocsOn = (float, int, str, tuple, list, dict)
    dontGetattrOn = (dict, list, set, tuple)
    for d in dir_comps:

        if d is None:
            continue

        if not filter(d):
            continue

        args = ''

        try:
            try:
                if isinstance(obj_to_complete, dontGetattrOn):
                    raise Exception(
                        'Since python 3.9, e.g. "dict[str]" will return'
                        " a dict that's only supposed to take strings. "
                        'Interestingly, e.g. dict["val"] is also valid '
                        'and presumably represents a dict that only takes '
                        'keys that are "val". This breaks our check for '
                        'class attributes.')
                obj = getattr(obj_to_complete.__class__, d)
            except:
                obj = getattr(obj_to_complete, d)
        except:  # just ignore and get it without additional info
            ret.append((d, '', args, TYPE_BUILTIN))
        else:

            if get_complete_info:
                try:
                    retType = TYPE_BUILTIN

                    # check if we have to get docs
                    getDoc = True
                    for class_ in dontGetDocsOn:

                        if isinstance(obj, class_):
                            getDoc = False
                            break

                    doc = ''
                    if getDoc:
                        # no need to get this info... too many constants are defined and
                        # makes things much slower (passing all that through sockets takes quite some time)
                        try:
                            doc = inspect.getdoc(obj)
                            if doc is None:
                                doc = ''
                        except:  # may happen on jython when checking java classes (so, just ignore it)
                            doc = ''

                    if inspect.ismethod(obj) or inspect.isbuiltin(
                            obj) or inspect.isfunction(
                                obj) or inspect.isroutine(obj):
                        try:
                            args, vargs, kwargs, defaults, kwonly_args, kwonly_defaults = getargspec(
                                obj)

                            args = args[:]

                            for kwonly_arg in kwonly_args:
                                default = kwonly_defaults.get(
                                    kwonly_arg, _SENTINEL)
                                if default is not _SENTINEL:
                                    args.append('%s=%s' %
                                                (kwonly_arg, default))
                                else:
                                    args.append(str(kwonly_arg))

                            args = '(%s)' % (', '.join(args))
                        except TypeError:
                            # ok, let's see if we can get the arguments from the doc
                            args, doc = signature_from_docstring(
                                doc, getattr(obj, '__name__', None))

                        retType = TYPE_FUNCTION

                    elif inspect.isclass(obj):
                        retType = TYPE_CLASS

                    elif inspect.ismodule(obj):
                        retType = TYPE_IMPORT

                    else:
                        retType = TYPE_ATTR

                    # add token and doc to return - assure only strings.
                    ret.append((d, doc, args, retType))

                except:  # just ignore and get it without aditional info
                    ret.append((d, '', args, TYPE_BUILTIN))

            else:  # get_complete_info == False
                if inspect.ismethod(obj) or inspect.isbuiltin(
                        obj) or inspect.isfunction(obj) or inspect.isroutine(
                            obj):
                    retType = TYPE_FUNCTION

                elif inspect.isclass(obj):
                    retType = TYPE_CLASS

                elif inspect.ismodule(obj):
                    retType = TYPE_IMPORT

                else:
                    retType = TYPE_ATTR
                # ok, no complete info, let's try to do this as fast and clean as possible
                # so, no docs for this kind of information, only the signatures
                ret.append((d, '', str(args), retType))

    return ret