Python __builtin__.isinstance() Examples

The following are 30 code examples of __builtin__.isinstance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module __builtin__ , or try the search function .
Example #1
Source File: unittest.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def isinstance(obj, clsinfo):
        import __builtin__
        if type(clsinfo) in (tuple, list):
            for cls in clsinfo:
                if cls is type: cls = types.ClassType
                if __builtin__.isinstance(obj, cls):
                    return 1
            return 0
        else: return __builtin__.isinstance(obj, clsinfo)


##############################################################################
# Test framework core
##############################################################################

# All classes defined herein are 'new-style' classes, allowing use of 'super()' 
Example #2
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _formatted_exception(exc):
    error_header_formstr = '{file}:{line}: '
    error_body_formstr = 'error: {errormsg} [{errorclass}]'
    if not isinstance(exc, FyppError):
        return error_body_formstr.format(
            errormsg=str(exc), errorclass=exc.__class__.__name__)
    out = []
    if exc.fname is not None:
        if exc.span[1] > exc.span[0] + 1:
            line = '{0}-{1}'.format(exc.span[0] + 1, exc.span[1])
        else:
            line = '{0}'.format(exc.span[0] + 1)
        out.append(error_header_formstr.format(file=exc.fname, line=line))
    out.append(error_body_formstr.format(errormsg=exc.msg,
                                         errorclass=exc.__class__.__name__))
    if exc.cause is not None:
        out.append('\n' + _formatted_exception(exc.cause))
    out.append('\n')
    return ''.join(out) 
Example #3
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_callable_argspec_py2(func):
    argspec = inspect.getargspec(func)
    varpos = argspec.varargs
    varkw = argspec.keywords
    args = argspec.args
    tuplearg = False
    for elem in args:
        tuplearg = tuplearg or isinstance(elem, list)
    if tuplearg:
        msg = 'tuple argument(s) found'
        raise FyppFatalError(msg)
    defaults = {}
    if argspec.defaults is not None:
        for ind, default in enumerate(argspec.defaults):
            iarg = len(args) - len(argspec.defaults) + ind
            defaults[args[iarg]] = default
    return args, defaults, varpos, varkw 
Example #4
Source File: parser.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def getResultSetId(self, top=None):
        if (
            fullResultSetNameCheck == 0 or
            self.boolean.value in ['not', 'prox']
        ):
            return ""

        if top is None:
            topLevel = 1
            top = self
        else:
            topLevel = 0

        # Iterate over operands and build a list
        rsList = []
        if isinstance(self.leftOperand, Triple):
            rsList.extend(self.leftOperand.getResultSetId(top))
        else:
            rsList.append(self.leftOperand.getResultSetId(top))
        if isinstance(self.rightOperand, Triple):
            rsList.extend(self.rightOperand.getResultSetId(top))
        else:
            rsList.append(self.rightOperand.getResultSetId(top))

        if topLevel == 1:
            # Check all elements are the same
            # if so we're a fubar form of present
            if (len(rsList) == rsList.count(rsList[0])):
                return rsList[0]
            else:
                return ""
        else:
            return rsList 
Example #5
Source File: parser.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def __getitem__(self, k):
        if isinstance(k, int):
            try:
                return self.modifiers[k]
            except:
                return None
        for m in self.modifiers:
            if (str(m.type) == k or m.type.value == k):
                return m
        return None 
Example #6
Source File: unittest.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def addTest(self, test):
        # sanity checks
        if not callable(test):
            raise TypeError("the test to add must be callable")
        if (isinstance(test, (type, types.ClassType)) and
            issubclass(test, (TestCase, TestSuite))):
            raise TypeError("TestCases and TestSuites must be instantiated "
                            "before passing them to addTest()")
        self._tests.append(test) 
Example #7
Source File: unittest.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def addTests(self, tests):
        if isinstance(tests, basestring):
            raise TypeError("tests must be an iterable of tests, not a string")
        for test in tests:
            self.addTest(test) 
Example #8
Source File: unittest.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def loadTestsFromModule(self, module):
        """Return a suite of all tests cases contained in the given module"""
        tests = []
        for name in dir(module):
            obj = getattr(module, name)
            if (isinstance(obj, (type, types.ClassType)) and
                issubclass(obj, TestCase)):
                tests.append(self.loadTestsFromTestCase(obj))
        return self.suiteClass(tests) 
Example #9
Source File: unittest.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def loadTestsFromName(self, name, module=None):
        """Return a suite of all tests cases given a string specifier.

        The name may resolve either to a module, a test case class, a
        test method within a test case class, or a callable object which
        returns a TestCase or TestSuite instance.

        The method optionally resolves the names relative to a given module.
        """
        parts = name.split('.')
        if module is None:
            parts_copy = parts[:]
            while parts_copy:
                try:
                    module = __import__('.'.join(parts_copy))
                    break
                except ImportError:
                    del parts_copy[-1]
                    if not parts_copy: raise
            parts = parts[1:]
        obj = module
        for part in parts:
            parent, obj = obj, getattr(obj, part)

        if type(obj) == types.ModuleType:
            return self.loadTestsFromModule(obj)
        elif (isinstance(obj, (type, types.ClassType)) and
              issubclass(obj, TestCase)):
            return self.loadTestsFromTestCase(obj)
        elif type(obj) == types.UnboundMethodType:
            return parent(obj.__name__)
        elif isinstance(obj, TestSuite):
            return obj
        elif callable(obj):
            test = obj()
            if not isinstance(test, (TestCase, TestSuite)):
                raise ValueError, \
                      "calling %s returned %s, not a test" % (obj,test)
            return test
        else:
            raise ValueError, "don't know how to make test from: %s" % obj 
Example #10
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parsefile(self, fobj):
        '''Parses file or a file like object.

        Args:
            fobj (str or file): Name of a file or a file like object.
        '''
        if isinstance(fobj, str):
            if fobj == STDIN:
                self._includefile(None, sys.stdin, STDIN, os.getcwd())
            else:
                inpfp = _open_input_file(fobj, self._encoding)
                self._includefile(None, inpfp, fobj, os.path.dirname(fobj))
                inpfp.close()
        else:
            self._includefile(None, fobj, FILEOBJ, os.getcwd()) 
Example #11
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _func_import(self, name, *_, **__):
        module = self._scope.get(name, None)
        if module is not None and isinstance(module, types.ModuleType):
            return module
        msg = "Import of module '{0}' via '__import__' not allowed".format(name)
        raise ImportError(msg) 
Example #12
Source File: misc.py    From gimp-plugin-export-layers with GNU General Public License v3.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)

    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #13
Source File: compatibility.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def isinstance20(a, typea):
        if type(typea) != type(type):
            raise TypeError("TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types")
        return type(typea) != typea 
Example #14
Source File: compatibility.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def reversed(data):
            if not isinstance(data, list):
                data = list(data)
            return data[::-1] 
Example #15
Source File: compatibility.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def reversed(data):
            if not isinstance(data, list):
                data = list(data)
            reversed_data = []
            for index in xrange(len(data)-1, -1, -1):
                reversed_data.append(data[index])
            return reversed_data

# --- sorted() from Python 2.4 --- 
Example #16
Source File: misc.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)

    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #17
Source File: misc.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)


    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #18
Source File: misc.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)


    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #19
Source File: compatibility.py    From ITWSV with MIT License 5 votes vote down vote up
def reversed(data):
            if not isinstance(data, list):
                data = list(data)
            reversed_data = []
            for index in xrange(len(data)-1, -1, -1):
                reversed_data.append(data[index])
            return reversed_data

# --- sorted() from Python 2.4 --- 
Example #20
Source File: misc.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)

    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #21
Source File: misc.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)

    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #22
Source File: py21compat.py    From earthengine with MIT License 5 votes vote down vote up
def isinstance(obj, t):
        if not __builtin__.isinstance(t, type(())):
            # t is not a tuple
            return __builtin__.isinstance(obj, _builtin_type_map.get(t, t))
        else:
            # t is a tuple
            for typ in t:
                if __builtin__.isinstance(obj, _builtin_type_map.get(typ, typ)):
                    return True
            return False

# vim:set ts=4 sw=4 sts=4 expandtab: 
Example #23
Source File: compatibility.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def isinstance20(a, typea):
        if type(typea) != type(type):
            raise TypeError("TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types")
        return type(typea) != typea 
Example #24
Source File: compatibility.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def reversed(data):
            if not isinstance(data, list):
                data = list(data)
            return data[::-1] 
Example #25
Source File: compatibility.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def reversed(data):
            if not isinstance(data, list):
                data = list(data)
            reversed_data = []
            for index in xrange(len(data)-1, -1, -1):
                reversed_data.append(data[index])
            return reversed_data

# --- sorted() from Python 2.4 --- 
Example #26
Source File: compatibility.py    From ITWSV with MIT License 5 votes vote down vote up
def isinstance20(a, typea):
        if type(typea) != type(type):
            raise TypeError("TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types")
        return type(typea) != typea 
Example #27
Source File: compatibility.py    From ITWSV with MIT License 5 votes vote down vote up
def reversed(data):
            if not isinstance(data, list):
                data = list(data)
            return data[::-1] 
Example #28
Source File: misc.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)

    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable 
Example #29
Source File: py21compat.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def isinstance(obj, t):
        if not __builtin__.isinstance(t, type(())):
            # t is not a tuple
            return __builtin__.isinstance(obj, _builtin_type_map.get(t, t))
        else:
            # t is a tuple
            for typ in t:
                if __builtin__.isinstance(obj, _builtin_type_map.get(typ, typ)):
                    return True
            return False

# vim:set ts=4 sw=4 sts=4 expandtab: 
Example #30
Source File: misc.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def pow(x, y, z=_SENTINEL):
        """
        pow(x, y[, z]) -> number

        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
        """
        # Handle newints
        if isinstance(x, newint):
            x = long(x)
        if isinstance(y, newint):
            y = long(y)
        if isinstance(z, newint):
            z = long(z)

        try:
            if z == _SENTINEL:
                return _builtin_pow(x, y)
            else:
                return _builtin_pow(x, y, z)
        except ValueError:
            if z == _SENTINEL:
                return _builtin_pow(x+0j, y)
            else:
                return _builtin_pow(x+0j, y, z)

    # ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
    #     callable = __builtin__.callable