Python types.InstanceType() Examples

The following are code examples for showing how to use types.InstanceType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: AshsSDK   Author: thehappydinoa   File: _base.py    MIT License 6 votes vote down vote up
def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)
            except BaseException:
                # Explicitly let all other new-style exceptions through so
                # that we can catch all old-style exceptions with a simple
                # "except:" clause below.
                #
                # All old-style exception objects are instances of
                # types.InstanceType, but "except types.InstanceType:" does
                # not catch old-style exceptions for some reason.  Thus, the
                # only way to catch all old-style exceptions without catching
                # any new-style exceptions is to filter out the new-style
                # exceptions, which all derive from BaseException.
                raise
            except:
                # Because of the BaseException clause above, this handler only
                # executes for old-style exception objects.
                LOGGER.exception('exception calling callback for %r', self) 
Example 2
Project: PythonUSBIP   Author: Frazew   File: USBIP.py    The Unlicense 6 votes vote down vote up
def formatDevicesList(self, devicesCount):

        pack_format = '>'
        i = 0
        for field in self._fields_:
            if (i == devicesCount + 2):
                break
            if type(field[1]) is types.InstanceType:
                if BaseStucture in field[1].__class__.__bases__:
                    pack_format += str(field[1].size()) + 's'
            elif 'si' == field[1]:
                pack_format += 'c'
            elif '<' in field[1]:
                pack_format += field[1][1:]
            else:
                pack_format += field[1]
            i += 1
        return pack_format 
Example 3
Project: PythonUSBIP   Author: Frazew   File: USBIP.py    The Unlicense 6 votes vote down vote up
def packDevicesList(self, devicesCount):
        values = []
        i = 0
        for field in self._fields_:
            if (i == devicesCount + 2):
                break
            if type(field[1]) is types.InstanceType:
                if BaseStucture in field[1].__class__.__bases__:
                     values.append(getattr(self, field[0], 0).pack())
            else:
                if 'si' == field[1]:
                    values.append(chr(getattr(self, field[0], 0)))
                else:
                    values.append(getattr(self, field[0], 0))
            i += 1
        return struct.pack(self.formatDevicesList(devicesCount), *values) 
Example 4
Project: Repobot   Author: Desgard   File: oinspect.py    MIT License 6 votes vote down vote up
def pdef(self, obj, oname=''):
        """Print the call signature for any callable object.

        If the object is a class, print the constructor information."""

        if not callable(obj):
            print('Object is not callable.')
            return

        header = ''

        if inspect.isclass(obj):
            header = self.__head('Class constructor information:\n')
        elif (not py3compat.PY3) and type(obj) is types.InstanceType:
            obj = obj.__call__

        output = self._getdef(obj,oname)
        if output is None:
            self.noinfo('definition header',oname)
        else:
            print(header,self.format(output), end=' ')

    # In Python 3, all classes are new-style, so they all have __init__. 
Example 5
Project: Repobot   Author: Desgard   File: traitlets.py    MIT License 6 votes vote down vote up
def error(self, obj, value):
        kind = type(value)
        if six.PY2 and kind is InstanceType:
            msg = 'class %s' % value.__class__.__name__
        else:
            msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )

        if obj is not None:
            e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
                % (self.name, class_of(obj),
                   self.info(), msg)
        else:
            e = "The '%s' trait must be %s, but a value of %r was specified." \
                % (self.name, self.info(), msg)

        raise TraitError(e) 
Example 6
Project: razzy-spinner   Author: rafasashi   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def in_idle():
    """
    @rtype: C{boolean}
    @return: true if this function is run within idle.  Tkinter
    programs that are run in idle should never call L{Tk.mainloop}; so
    this function should be used to gate all calls to C{Tk.mainloop}.

    @warning: This function works by checking C{sys.stdin}.  If the
    user has modified C{sys.stdin}, then it may return incorrect
    results.
    """
    import sys, types
    return (type(sys.stdin) == types.InstanceType and \
            sys.stdin.__class__.__name__ == 'PyShell')

##//////////////////////////////////////////////////////
##  Test code.
##////////////////////////////////////////////////////// 
Example 7
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def in_idle():
    """
    @rtype: C{boolean}
    @return: true if this function is run within idle.  Tkinter
    programs that are run in idle should never call L{Tk.mainloop}; so
    this function should be used to gate all calls to C{Tk.mainloop}.

    @warning: This function works by checking C{sys.stdin}.  If the
    user has modified C{sys.stdin}, then it may return incorrect
    results.
    """
    import sys, types
    return (type(sys.stdin) == types.InstanceType and \
            sys.stdin.__class__.__name__ == 'PyShell')

##//////////////////////////////////////////////////////
##  Test code.
##////////////////////////////////////////////////////// 
Example 8
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 6 votes vote down vote up
def init_info(self):
        scxx_converter.init_info(self)
        self.type_name = 'instance'
        self.check_func = 'PyInstance_Check'
        self.c_type = 'py::object'
        self.return_type = 'py::object'
        self.to_c_return = 'py::object(py_obj)'
        self.matching_types = [types.InstanceType]
        # ref counting handled by py::object
        self.use_ref_count = 0

#----------------------------------------------------------------------------
# Catchall Converter
#
# catch all now handles callable objects
#---------------------------------------------------------------------------- 
Example 9
Project: grand_central   Author: amiracle   File: _base.py    MIT License 6 votes vote down vote up
def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)
            except BaseException:
                # Explicitly let all other new-style exceptions through so
                # that we can catch all old-style exceptions with a simple
                # "except:" clause below.
                #
                # All old-style exception objects are instances of
                # types.InstanceType, but "except types.InstanceType:" does
                # not catch old-style exceptions for some reason.  Thus, the
                # only way to catch all old-style exceptions without catching
                # any new-style exceptions is to filter out the new-style
                # exceptions, which all derive from BaseException.
                raise
            except:
                # Because of the BaseException clause above, this handler only
                # executes for old-style exception objects.
                LOGGER.exception('exception calling callback for %r', self) 
Example 10
Project: TESTGIT   Author: B-ROY   File: feedparser.py    Apache License 2.0 6 votes vote down vote up
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]):
    '''Parse a feed from a URL, file, stream, or string'''
    result = FeedParserDict()
    result['feed'] = FeedParserDict()
    result['entries'] = []
    if _XML_AVAILABLE:
        result['bozo'] = 0
    if type(handlers) == types.InstanceType:
        handlers = [handlers]
    try:
        f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers)
        data = f.read()
    except Exception, e:
        result['bozo'] = 1
        result['bozo_exception'] = e
        data = ''
        f = None

    # if feed is gzip-compressed, decompress it 
Example 11
Project: ithz   Author: ergoithz   File: feedparser.py    MIT License 6 votes vote down vote up
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]):
    '''Parse a feed from a URL, file, stream, or string'''
    result = FeedParserDict()
    result['feed'] = FeedParserDict()
    result['entries'] = []
    if _XML_AVAILABLE:
        result['bozo'] = 0
    if type(handlers) == types.InstanceType:
        handlers = [handlers]
    try:
        f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers)
        data = f.read()
    except Exception, e:
        result['bozo'] = 1
        result['bozo_exception'] = e
        data = ''
        f = None

    # if feed is gzip-compressed, decompress it 
Example 12
Project: open-recipe   Author: dspray95   File: rebuild.py    The Unlicense 6 votes vote down vote up
def latestVersionOf(self, anObject):
        """
        Get the latest version of an object.

        This can handle just about anything callable; instances, functions,
        methods, and classes.
        """
        t = type(anObject)
        if t == types.FunctionType:
            return latestFunction(anObject)
        elif t == types.MethodType:
            if anObject.__self__ is None:
                return getattr(anObject.im_class, anObject.__name__)
            else:
                return getattr(anObject.__self__, anObject.__name__)
        elif not _PY3 and t == InstanceType:
            # Kick it, if it's out of date.
            getattr(anObject, 'nothing', None)
            return anObject
        elif _isClassType(t):
            return latestClass(anObject)
        else:
            log.msg('warning returning anObject!')
            return anObject 
Example 13
Project: Computable   Author: ktraunmueller   File: traitlets.py    MIT License 6 votes vote down vote up
def error(self, obj, value):
        kind = type(value)
        if (not py3compat.PY3) and kind is InstanceType:
            msg = 'class %s' % value.__class__.__name__
        else:
            msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )

        if obj is not None:
            e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
                % (self.name, class_of(obj),
                   self.info(), msg)
        else:
            e = "The '%s' trait must be %s, but a value of %r was specified." \
                % (self.name, self.info(), msg)

        raise TraitError(e) 
Example 14
Project: Computable   Author: ktraunmueller   File: oinspect.py    MIT License 6 votes vote down vote up
def pdef(self, obj, oname=''):
        """Print the call signature for any callable object.

        If the object is a class, print the constructor information."""

        if not callable(obj):
            print('Object is not callable.')
            return

        header = ''

        if inspect.isclass(obj):
            header = self.__head('Class constructor information:\n')
            obj = obj.__init__
        elif (not py3compat.PY3) and type(obj) is types.InstanceType:
            obj = obj.__call__

        output = self._getdef(obj,oname)
        if output is None:
            self.noinfo('definition header',oname)
        else:
            print(header,self.format(output), end=' ', file=io.stdout)

    # In Python 3, all classes are new-style, so they all have __init__. 
Example 15
Project: Computable   Author: ktraunmueller   File: c_spec.py    MIT License 6 votes vote down vote up
def init_info(self):
        scxx_converter.init_info(self)
        self.type_name = 'instance'
        self.check_func = 'PyInstance_Check'
        self.c_type = 'py::object'
        self.return_type = 'py::object'
        self.to_c_return = 'py::object(py_obj)'
        self.matching_types = [types.InstanceType]
        # ref counting handled by py::object
        self.use_ref_count = 0

#----------------------------------------------------------------------------
# Catchall Converter
#
# catch all now handles callable objects
#---------------------------------------------------------------------------- 
Example 16
Project: pyblish-win   Author: pyblish   File: dis.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if isinstance(x, types.InstanceType):
        x = x.__class__
    if hasattr(x, 'im_func'):
        x = x.im_func
    if hasattr(x, 'func_code'):
        x = x.func_code
    if hasattr(x, '__dict__'):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if isinstance(x1, _have_code):
                print "Disassembly of %s:" % name
                try:
                    dis(x1)
                except TypeError, msg:
                    print "Sorry:", msg
                print 
Example 17
Project: pyblish-win   Author: pyblish   File: pydoc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def describe(thing):
    """Produce a short description of the given thing."""
    if inspect.ismodule(thing):
        if thing.__name__ in sys.builtin_module_names:
            return 'built-in module ' + thing.__name__
        if hasattr(thing, '__path__'):
            return 'package ' + thing.__name__
        else:
            return 'module ' + thing.__name__
    if inspect.isbuiltin(thing):
        return 'built-in function ' + thing.__name__
    if inspect.isgetsetdescriptor(thing):
        return 'getset descriptor %s.%s.%s' % (
            thing.__objclass__.__module__, thing.__objclass__.__name__,
            thing.__name__)
    if inspect.ismemberdescriptor(thing):
        return 'member descriptor %s.%s.%s' % (
            thing.__objclass__.__module__, thing.__objclass__.__name__,
            thing.__name__)
    if inspect.isclass(thing):
        return 'class ' + thing.__name__
    if inspect.isfunction(thing):
        return 'function ' + thing.__name__
    if inspect.ismethod(thing):
        return 'method ' + thing.__name__
    if type(thing) is types.InstanceType:
        return 'instance of ' + thing.__class__.__name__
    return type(thing).__name__ 
Example 18
Project: pyblish-win   Author: pyblish   File: test_dbshelve.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def checkrec(self, key, value):
        # override this in a subclass if the key type is different

        if sys.version_info[0] >= 3 :
            if isinstance(key, bytes) :
                key = key.decode("iso8859-1")  # 8 bits

        x = key[1]
        if key[0] == 'S':
            self.assertEqual(type(value), str)
            self.assertEqual(value, 10 * x)

        elif key[0] == 'I':
            self.assertEqual(type(value), int)
            self.assertEqual(value, ord(x))

        elif key[0] == 'L':
            self.assertEqual(type(value), list)
            self.assertEqual(value, [x] * 10)

        elif key[0] == 'O':
            if sys.version_info[0] < 3 :
                from types import InstanceType
                self.assertEqual(type(value), InstanceType)
            else :
                self.assertEqual(type(value), DataClass)

            self.assertEqual(value.S, 10 * x)
            self.assertEqual(value.I, ord(x))
            self.assertEqual(value.L, [x] * 10)

        else:
            self.assertTrue(0, 'Unknown key type, fix the test')

#---------------------------------------------------------------------- 
Example 19
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _getmethods(obj, methods):
    # Helper to get a list of methods from an object
    # Adds names to dictionary argument 'methods'
    for name in dir(obj):
        attr = getattr(obj, name)
        if hasattr(attr, '__call__'):
            methods[name] = 1
    if type(obj) == types.InstanceType:
        _getmethods(obj.__class__, methods)
    if type(obj) == types.ClassType:
        for super in obj.__bases__:
            _getmethods(super, methods) 
Example 20
Project: AshsSDK   Author: thehappydinoa   File: representer.py    MIT License 5 votes vote down vote up
def represent_data(self, data):
        if self.ignore_aliases(data):
            self.alias_key = None
        else:
            self.alias_key = id(data)
        if self.alias_key is not None:
            if self.alias_key in self.represented_objects:
                node = self.represented_objects[self.alias_key]
                #if node is None:
                #    raise RepresenterError("recursive objects are not allowed: %r" % data)
                return node
            #self.represented_objects[alias_key] = None
            self.object_keeper.append(data)
        data_types = type(data).__mro__
        if type(data) is types.InstanceType:
            data_types = self.get_classobj_bases(data.__class__)+list(data_types)
        if data_types[0] in self.yaml_representers:
            node = self.yaml_representers[data_types[0]](self, data)
        else:
            for data_type in data_types:
                if data_type in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[data_type](self, data)
                    break
            else:
                if None in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[None](self, data)
                elif None in self.yaml_representers:
                    node = self.yaml_representers[None](self, data)
                else:
                    node = ScalarNode(None, unicode(data))
        #if alias_key is not None:
        #    self.represented_objects[alias_key] = node
        return node 
Example 21
Project: AshsSDK   Author: thehappydinoa   File: _base.py    MIT License 5 votes vote down vote up
def __get_result(self):
        if self._exception:
            if isinstance(self._exception, types.InstanceType):
                # The exception is an instance of an old-style class, which
                # means type(self._exception) returns types.ClassType instead
                # of the exception's actual class type.
                exception_type = self._exception.__class__
            else:
                exception_type = type(self._exception)
            raise exception_type, self._exception, self._traceback
        else:
            return self._result 
Example 22
Project: PythonUSBIP   Author: Frazew   File: USBIP.py    The Unlicense 5 votes vote down vote up
def format(self):

        pack_format = '>'
        for field in self._fields_:
            if type(field[1]) is types.InstanceType:
                if BaseStucture in field[1].__class__.__bases__:
                    pack_format += str(field[1].size()) + 's'
            elif 'si' == field[1]:
                pack_format += 'c'
            elif '<' in field[1]:
                pack_format += field[1][1:]
            else:
                pack_format += field[1]
        return pack_format 
Example 23
Project: PythonUSBIP   Author: Frazew   File: USBIP.py    The Unlicense 5 votes vote down vote up
def pack(self):
        values = []
        for field in self._fields_:
            if type(field[1]) is types.InstanceType:
                if BaseStucture in field[1].__class__.__bases__:
                     values.append(getattr(self, field[0], 0).pack())
            else:
                if 'si' == field[1]:
                    values.append(chr(getattr(self, field[0], 0)))
                else:
                    values.append(getattr(self, field[0], 0))
        return struct.pack(self.format(), *values) 
Example 24
Project: Repobot   Author: Desgard   File: ultratb.py    MIT License 5 votes vote down vote up
def format_exception(self, etype, evalue):
        colors = self.Colors  # just a shorthand + quicker name lookup
        colorsnormal = colors.Normal  # used a lot
        indent = ' ' * INDENT_SIZE
        # Get (safely) a string form of the exception info
        try:
            etype_str, evalue_str = map(str, (etype, evalue))
        except:
            # User exception is improperly defined.
            etype, evalue = str, sys.exc_info()[:2]
            etype_str, evalue_str = map(str, (etype, evalue))
        # ... and format it
        exception = ['%s%s%s: %s' % (colors.excName, etype_str,
                                     colorsnormal, py3compat.cast_unicode(evalue_str))]

        if (not py3compat.PY3) and type(evalue) is types.InstanceType:
            try:
                names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
            except:
                # Every now and then, an object with funny internals blows up
                # when dir() is called on it.  We do the best we can to report
                # the problem and continue
                _m = '%sException reporting error (object with broken dir())%s:'
                exception.append(_m % (colors.excName, colorsnormal))
                etype_str, evalue_str = map(str, sys.exc_info()[:2])
                exception.append('%s%s%s: %s' % (colors.excName, etype_str,
                                                 colorsnormal, py3compat.cast_unicode(evalue_str)))
                names = []
            for name in names:
                value = text_repr(getattr(evalue, name))
                exception.append('\n%s%s = %s' % (indent, name, value))

        return exception 
Example 25
Project: Repobot   Author: Desgard   File: traitlets.py    MIT License 5 votes vote down vote up
def repr_type(obj):
    """ Return a string representation of a value and its type for readable
    error messages.
    """
    the_type = type(obj)
    if six.PY2 and the_type is InstanceType:
        # Old-style class.
        the_type = obj.__class__
    msg = '%r %r' % (obj, the_type)
    return msg 
Example 26
Project: razzy-spinner   Author: rafasashi   File: kimmo.py    GNU General Public License v3.0 5 votes vote down vote up
def _classeq(instance1, instance2):
    """
    @return: true iff the given objects are instances of the same
        class.
    @rtype: C{bool}
    """
    return (type(instance1) == types.InstanceType and
            type(instance2) == types.InstanceType and
            instance1.__class__ == instance2.__class__)

# given a dot string, write to a tmp file and invoke the grapher
# return a filename to open.
# imagetype is hardcoded for now 
Example 27
Project: misp42splunk   Author: remg427   File: representer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def represent_data(self, data):
        if self.ignore_aliases(data):
            self.alias_key = None
        else:
            self.alias_key = id(data)
        if self.alias_key is not None:
            if self.alias_key in self.represented_objects:
                node = self.represented_objects[self.alias_key]
                #if node is None:
                #    raise RepresenterError("recursive objects are not allowed: %r" % data)
                return node
            #self.represented_objects[alias_key] = None
            self.object_keeper.append(data)
        data_types = type(data).__mro__
        if type(data) is types.InstanceType:
            data_types = self.get_classobj_bases(data.__class__)+list(data_types)
        if data_types[0] in self.yaml_representers:
            node = self.yaml_representers[data_types[0]](self, data)
        else:
            for data_type in data_types:
                if data_type in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[data_type](self, data)
                    break
            else:
                if None in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[None](self, data)
                elif None in self.yaml_representers:
                    node = self.yaml_representers[None](self, data)
                else:
                    node = ScalarNode(None, unicode(data))
        #if alias_key is not None:
        #    self.represented_objects[alias_key] = node
        return node 
Example 28
Project: RvMake   Author: Ahuge   File: representer.py    GNU General Public License v3.0 5 votes vote down vote up
def represent_data(self, data):
        if self.ignore_aliases(data):
            self.alias_key = None
        else:
            self.alias_key = id(data)
        if self.alias_key is not None:
            if self.alias_key in self.represented_objects:
                node = self.represented_objects[self.alias_key]
                #if node is None:
                #    raise RepresenterError("recursive objects are not allowed: %r" % data)
                return node
            #self.represented_objects[alias_key] = None
            self.object_keeper.append(data)
        data_types = type(data).__mro__
        if type(data) is types.InstanceType:
            data_types = self.get_classobj_bases(data.__class__)+list(data_types)
        if data_types[0] in self.yaml_representers:
            node = self.yaml_representers[data_types[0]](self, data)
        else:
            for data_type in data_types:
                if data_type in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[data_type](self, data)
                    break
            else:
                if None in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[None](self, data)
                elif None in self.yaml_representers:
                    node = self.yaml_representers[None](self, data)
                else:
                    node = ScalarNode(None, unicode(data))
        #if alias_key is not None:
        #    self.represented_objects[alias_key] = node
        return node 
Example 29
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: parameterized.py    MIT License 5 votes vote down vote up
def __call__(self, test_func):
        self.assert_not_in_testcase_subclass()

        @wraps(test_func)
        def wrapper(test_self=None):
            test_cls = test_self and type(test_self)
            if test_self is not None:
                if issubclass(test_cls, InstanceType):
                    raise TypeError((
                        "@parameterized can't be used with old-style classes, but "
                        "%r has an old-style class. Consider using a new-style "
                        "class, or '@parameterized.expand' "
                        "(see http://stackoverflow.com/q/54867/71522 for more "
                        "information on old-style classes)."
                    ) %(test_self, ))

            original_doc = wrapper.__doc__
            for num, args in enumerate(wrapper.parameterized_input):
                p = param.from_decorator(args)
                unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
                try:
                    wrapper.__doc__ = nose_tuple[0].__doc__
                    # Nose uses `getattr(instance, test_func.__name__)` to get
                    # a method bound to the test instance (as opposed to a
                    # method bound to the instance of the class created when
                    # tests were being enumerated). Set a value here to make
                    # sure nose can get the correct test method.
                    if test_self is not None:
                        setattr(test_cls, test_func.__name__, unbound_func)
                    yield nose_tuple
                finally:
                    if test_self is not None:
                        delattr(test_cls, test_func.__name__)
                    wrapper.__doc__ = original_doc
        wrapper.parameterized_input = self.get_input()
        wrapper.parameterized_func = test_func
        test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
        return wrapper 
Example 30
Project: recruit   Author: Frank-qlu   File: parameterized.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, test_func):
        self.assert_not_in_testcase_subclass()

        @wraps(test_func)
        def wrapper(test_self=None):
            test_cls = test_self and type(test_self)
            if test_self is not None:
                if issubclass(test_cls, InstanceType):
                    raise TypeError((
                        "@parameterized can't be used with old-style classes, but "
                        "%r has an old-style class. Consider using a new-style "
                        "class, or '@parameterized.expand' "
                        "(see http://stackoverflow.com/q/54867/71522 for more "
                        "information on old-style classes)."
                    ) %(test_self, ))

            original_doc = wrapper.__doc__
            for num, args in enumerate(wrapper.parameterized_input):
                p = param.from_decorator(args)
                unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
                try:
                    wrapper.__doc__ = nose_tuple[0].__doc__
                    # Nose uses `getattr(instance, test_func.__name__)` to get
                    # a method bound to the test instance (as opposed to a
                    # method bound to the instance of the class created when
                    # tests were being enumerated). Set a value here to make
                    # sure nose can get the correct test method.
                    if test_self is not None:
                        setattr(test_cls, test_func.__name__, unbound_func)
                    yield nose_tuple
                finally:
                    if test_self is not None:
                        delattr(test_cls, test_func.__name__)
                    wrapper.__doc__ = original_doc
        wrapper.parameterized_input = self.get_input()
        wrapper.parameterized_func = test_func
        test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
        return wrapper 
Example 31
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: accelerate_tools.py    GNU General Public License v3.0 5 votes vote down vote up
def lookup_type(x):
    T = type(x)
    try:
        return typedefs[T]
    except:
        if isinstance(T,np.ndarray):
            return typedefs[(T,len(x.shape),x.dtype.char)]
        elif issubclass(T, InstanceType):
            return Instance(x)
        else:
            raise NotImplementedError(T)

##################################################################
#                        class ACCELERATE                        #
################################################################## 
Example 32
Project: grand_central   Author: amiracle   File: _base.py    MIT License 5 votes vote down vote up
def __get_result(self):
        if self._exception:
            if isinstance(self._exception, types.InstanceType):
                # The exception is an instance of an old-style class, which
                # means type(self._exception) returns types.ClassType instead
                # of the exception's actual class type.
                exception_type = self._exception.__class__
            else:
                exception_type = type(self._exception)
            raise exception_type, self._exception, self._traceback
        else:
            return self._result 
Example 33
Project: tf-pose   Author: SrikanthVelpuri   File: debug.py    Apache License 2.0 5 votes vote down vote up
def typeStr(obj):
    """Create a more useful type string by making <instance> types report their class."""
    typ = type(obj)
    if typ == getattr(types, 'InstanceType', None):
        return "<instance of %s>" % obj.__class__.__name__
    else:
        return str(typ) 
Example 34
Project: FUTU_Stop_Loss   Author: BigtoC   File: parameterized.py    MIT License 5 votes vote down vote up
def __call__(self, test_func):
        self.assert_not_in_testcase_subclass()

        @wraps(test_func)
        def wrapper(test_self=None):
            test_cls = test_self and type(test_self)
            if test_self is not None:
                if issubclass(test_cls, InstanceType):
                    raise TypeError((
                        "@parameterized can't be used with old-style classes, but "
                        "%r has an old-style class. Consider using a new-style "
                        "class, or '@parameterized.expand' "
                        "(see http://stackoverflow.com/q/54867/71522 for more "
                        "information on old-style classes)."
                    ) %(test_self, ))

            original_doc = wrapper.__doc__
            for num, args in enumerate(wrapper.parameterized_input):
                p = param.from_decorator(args)
                unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
                try:
                    wrapper.__doc__ = nose_tuple[0].__doc__
                    # Nose uses `getattr(instance, test_func.__name__)` to get
                    # a method bound to the test instance (as opposed to a
                    # method bound to the instance of the class created when
                    # tests were being enumerated). Set a value here to make
                    # sure nose can get the correct test method.
                    if test_self is not None:
                        setattr(test_cls, test_func.__name__, unbound_func)
                    yield nose_tuple
                finally:
                    if test_self is not None:
                        delattr(test_cls, test_func.__name__)
                    wrapper.__doc__ = original_doc
        wrapper.parameterized_input = self.get_input()
        wrapper.parameterized_func = test_func
        test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
        return wrapper 
Example 35
Project: rpython-lang-scheme   Author: tomoh1r   File: disassembler.py    MIT License 5 votes vote down vote up
def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if type(x) is types.InstanceType:
        x = x.__class__
    if hasattr(x, 'im_func'):
        x = x.im_func
    if hasattr(x, 'func_code'):
        x = x.func_code
    if hasattr(x, '__dict__'):
        xxx
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if type(x1) in (types.MethodType,
                            types.FunctionType,
                            types.CodeType,
                            types.ClassType):
                print("Disassembly of %s:" % name)
                try:
                    dis(x1)
                except TypeError, msg:
                    print("Sorry:", msg)
                print() 
Example 36
Project: rpython-lang-scheme   Author: tomoh1r   File: objectmodel.py    MIT License 5 votes vote down vote up
def instantiate(cls, nonmovable=False):
    "Create an empty instance of 'cls'."
    if isinstance(cls, type):
        return cls.__new__(cls)
    else:
        return types.InstanceType(cls) 
Example 37
Project: ironpython2   Author: IronLanguages   File: dis.py    Apache License 2.0 5 votes vote down vote up
def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if isinstance(x, types.InstanceType):
        x = x.__class__
    if hasattr(x, 'im_func'):
        x = x.im_func
    if hasattr(x, 'func_code'):
        x = x.func_code
    if hasattr(x, '__dict__'):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if isinstance(x1, _have_code):
                print "Disassembly of %s:" % name
                try:
                    dis(x1)
                except TypeError, msg:
                    print "Sorry:", msg
                print 
Example 38
Project: ironpython2   Author: IronLanguages   File: pydoc.py    Apache License 2.0 5 votes vote down vote up
def describe(thing):
    """Produce a short description of the given thing."""
    if inspect.ismodule(thing):
        if thing.__name__ in sys.builtin_module_names:
            return 'built-in module ' + thing.__name__
        if hasattr(thing, '__path__'):
            return 'package ' + thing.__name__
        else:
            return 'module ' + thing.__name__
    if inspect.isbuiltin(thing):
        return 'built-in function ' + thing.__name__
    if inspect.isgetsetdescriptor(thing):
        return 'getset descriptor %s.%s.%s' % (
            thing.__objclass__.__module__, thing.__objclass__.__name__,
            thing.__name__)
    if inspect.ismemberdescriptor(thing):
        return 'member descriptor %s.%s.%s' % (
            thing.__objclass__.__module__, thing.__objclass__.__name__,
            thing.__name__)
    if inspect.isclass(thing):
        return 'class ' + thing.__name__
    if inspect.isfunction(thing):
        return 'function ' + thing.__name__
    if inspect.ismethod(thing):
        return 'method ' + thing.__name__
    if type(thing) is types.InstanceType:
        return 'instance of ' + thing.__class__.__name__
    return type(thing).__name__ 
Example 39
Project: ironpython2   Author: IronLanguages   File: test_dbshelve.py    Apache License 2.0 5 votes vote down vote up
def checkrec(self, key, value):
        # override this in a subclass if the key type is different

        if sys.version_info[0] >= 3 :
            if isinstance(key, bytes) :
                key = key.decode("iso8859-1")  # 8 bits

        x = key[1]
        if key[0] == 'S':
            self.assertEqual(type(value), str)
            self.assertEqual(value, 10 * x)

        elif key[0] == 'I':
            self.assertEqual(type(value), int)
            self.assertEqual(value, ord(x))

        elif key[0] == 'L':
            self.assertEqual(type(value), list)
            self.assertEqual(value, [x] * 10)

        elif key[0] == 'O':
            if sys.version_info[0] < 3 :
                from types import InstanceType
                self.assertEqual(type(value), InstanceType)
            else :
                self.assertEqual(type(value), DataClass)

            self.assertEqual(value.S, 10 * x)
            self.assertEqual(value.I, ord(x))
            self.assertEqual(value.L, [x] * 10)

        else:
            self.fail('Unknown key type, fix the test')

#---------------------------------------------------------------------- 
Example 40
Project: MARRtino-2.0   Author: DaniAffCH   File: parameterized.py    GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, test_func):
        self.assert_not_in_testcase_subclass()

        @wraps(test_func)
        def wrapper(test_self=None):
            test_cls = test_self and type(test_self)
            if test_self is not None:
                if issubclass(test_cls, InstanceType):
                    raise TypeError((
                        "@parameterized can't be used with old-style classes, but "
                        "%r has an old-style class. Consider using a new-style "
                        "class, or '@parameterized.expand' "
                        "(see http://stackoverflow.com/q/54867/71522 for more "
                        "information on old-style classes)."
                    ) %(test_self, ))

            original_doc = wrapper.__doc__
            for num, args in enumerate(wrapper.parameterized_input):
                p = param.from_decorator(args)
                unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
                try:
                    wrapper.__doc__ = nose_tuple[0].__doc__
                    # Nose uses `getattr(instance, test_func.__name__)` to get
                    # a method bound to the test instance (as opposed to a
                    # method bound to the instance of the class created when
                    # tests were being enumerated). Set a value here to make
                    # sure nose can get the correct test method.
                    if test_self is not None:
                        setattr(test_cls, test_func.__name__, unbound_func)
                    yield nose_tuple
                finally:
                    if test_self is not None:
                        delattr(test_cls, test_func.__name__)
                    wrapper.__doc__ = original_doc
        wrapper.parameterized_input = self.get_input()
        wrapper.parameterized_func = test_func
        test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
        return wrapper 
Example 41
Project: MARRtino-2.0   Author: DaniAffCH   File: contextlib2.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_type(obj):
        obj_type = type(obj)
        if obj_type is InstanceType:
            return obj.__class__  # Old-style class
        return obj_type  # New-style class


# Inspired by discussions on http://bugs.python.org/issue13585 
Example 42
Project: git_for_splunk   Author: ChrisYounger   File: representer.py    Apache License 2.0 5 votes vote down vote up
def represent_data(self, data):
        if self.ignore_aliases(data):
            self.alias_key = None
        else:
            self.alias_key = id(data)
        if self.alias_key is not None:
            if self.alias_key in self.represented_objects:
                node = self.represented_objects[self.alias_key]
                #if node is None:
                #    raise RepresenterError("recursive objects are not allowed: %r" % data)
                return node
            #self.represented_objects[alias_key] = None
            self.object_keeper.append(data)
        data_types = type(data).__mro__
        if type(data) is types.InstanceType:
            data_types = self.get_classobj_bases(data.__class__)+list(data_types)
        if data_types[0] in self.yaml_representers:
            node = self.yaml_representers[data_types[0]](self, data)
        else:
            for data_type in data_types:
                if data_type in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[data_type](self, data)
                    break
            else:
                if None in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[None](self, data)
                elif None in self.yaml_representers:
                    node = self.yaml_representers[None](self, data)
                else:
                    node = ScalarNode(None, unicode(data))
        #if alias_key is not None:
        #    self.represented_objects[alias_key] = node
        return node 
Example 43
Project: open-recipe   Author: dspray95   File: _json.py    The Unlicense 5 votes vote down vote up
def failureFromJSON(failureDict):
    """
    Load a L{Failure} from a dictionary deserialized from JSON.

    @param failureDict: a JSON-deserialized object like one previously returned
        by L{failureAsJSON}.
    @type failureDict: L{dict} mapping L{unicode} to attributes

    @return: L{Failure}
    @rtype: L{Failure}
    """
    # InstanceType() is only available in Python 2 and lower.
    # __new__ is only available on new-style classes.
    newFailure = getattr(Failure, "__new__", None)
    if newFailure is None:
        f = types.InstanceType(Failure)
    else:
        f = newFailure(Failure)

    if not _PY3:
        # Python 2 needs the failure dictionary as purely bytes, not text
        failureDict = asBytes(failureDict)

    typeInfo = failureDict["type"]
    failureDict["type"] = type(typeInfo["__name__"], (), typeInfo)
    f.__dict__ = failureDict
    return f 
Example 44
Project: vnpy_crypto   Author: birforce   File: parameterized.py    MIT License 5 votes vote down vote up
def __call__(self, test_func):
        self.assert_not_in_testcase_subclass()

        @wraps(test_func)
        def wrapper(test_self=None):
            test_cls = test_self and type(test_self)
            if test_self is not None:
                if issubclass(test_cls, InstanceType):
                    raise TypeError((
                        "@parameterized can't be used with old-style classes, but "
                        "%r has an old-style class. Consider using a new-style "
                        "class, or '@parameterized.expand' "
                        "(see http://stackoverflow.com/q/54867/71522 for more "
                        "information on old-style classes)."
                    ) %(test_self, ))

            original_doc = wrapper.__doc__
            for num, args in enumerate(wrapper.parameterized_input):
                p = param.from_decorator(args)
                unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
                try:
                    wrapper.__doc__ = nose_tuple[0].__doc__
                    # Nose uses `getattr(instance, test_func.__name__)` to get
                    # a method bound to the test instance (as opposed to a
                    # method bound to the instance of the class created when
                    # tests were being enumerated). Set a value here to make
                    # sure nose can get the correct test method.
                    if test_self is not None:
                        setattr(test_cls, test_func.__name__, unbound_func)
                    yield nose_tuple
                finally:
                    if test_self is not None:
                        delattr(test_cls, test_func.__name__)
                    wrapper.__doc__ = original_doc
        wrapper.parameterized_input = self.get_input()
        wrapper.parameterized_func = test_func
        test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
        return wrapper 
Example 45
Project: IronHydra   Author: microdee   File: dis.py    MIT License 5 votes vote down vote up
def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if isinstance(x, types.InstanceType):
        x = x.__class__
    if hasattr(x, 'im_func'):
        x = x.im_func
    if hasattr(x, 'func_code'):
        x = x.func_code
    if hasattr(x, '__dict__'):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if isinstance(x1, _have_code):
                print "Disassembly of %s:" % name
                try:
                    dis(x1)
                except TypeError, msg:
                    print "Sorry:", msg
                print 
Example 46
Project: IronHydra   Author: microdee   File: pydoc.py    MIT License 5 votes vote down vote up
def describe(thing):
    """Produce a short description of the given thing."""
    if inspect.ismodule(thing):
        if thing.__name__ in sys.builtin_module_names:
            return 'built-in module ' + thing.__name__
        if hasattr(thing, '__path__'):
            return 'package ' + thing.__name__
        else:
            return 'module ' + thing.__name__
    if inspect.isbuiltin(thing):
        return 'built-in function ' + thing.__name__
    if inspect.isgetsetdescriptor(thing):
        return 'getset descriptor %s.%s.%s' % (
            thing.__objclass__.__module__, thing.__objclass__.__name__,
            thing.__name__)
    if inspect.ismemberdescriptor(thing):
        return 'member descriptor %s.%s.%s' % (
            thing.__objclass__.__module__, thing.__objclass__.__name__,
            thing.__name__)
    if inspect.isclass(thing):
        return 'class ' + thing.__name__
    if inspect.isfunction(thing):
        return 'function ' + thing.__name__
    if inspect.ismethod(thing):
        return 'method ' + thing.__name__
    if type(thing) is types.InstanceType:
        return 'instance of ' + thing.__class__.__name__
    return type(thing).__name__ 
Example 47
Project: air-quick-fix   Author: jamesward   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_class_alias(klass):
    """
    Finds the alias registered to the class.

    @type klass: C{object} or class
    @raise UnknownClassAlias: Class not found.
    @raise TypeError: Expecting C{string} or C{class} type.

    @rtype: L{ClassAlias}
    @return: The class alias linked to the C{klass}.
    """
    if not isinstance(klass, (type, types.ClassType, basestring)):
        if isinstance(klass, types.InstanceType):
            klass = klass.__class__
        elif isinstance(klass, types.ObjectType):
            klass = type(klass)

    if isinstance(klass, basestring):
        for a, k in CLASS_CACHE.iteritems():
            if klass == a:
                return k
    else:
        for a, k in CLASS_CACHE.iteritems():
            if klass == k.klass:
                return k

    if isinstance(klass, basestring):
        return load_class(klass)

    raise UnknownClassAlias, "Unknown alias %s" % klass 
Example 48
Project: air-quick-fix   Author: jamesward   File: amf3.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getClassDefinitionReference(self, class_def):
        """
        Return class definition reference.

        @type class_def: L{ClassDefinition} or C{instance} or C{class}
        @param class_def: The class definition reference to be found.
        @raise ReferenceError: The reference could not be found.
        @return: The reference to C{class_def}.
        @rtype: C{int}
        """
        if not isinstance(class_def, ClassDefinition):
            if isinstance(class_def, (type, types.ClassType)):
                try:
                    return self.rev_class_defs[class_def]
                except KeyError:
                    raise pyamf.ReferenceError("Reference for class definition for %s not found" %
                        class_def)
            elif isinstance(class_def, (types.InstanceType, types.ObjectType)):
                try:
                    return self.class_defs[class_def.__class__]
                except KeyError:
                    raise pyamf.ReferenceError("Reference for class definition for %s not found" %
                        class_def.__class__)

            raise TypeError, 'unable to determine class for %r' % class_def
        else:
            try:
                return self.rev_class_defs[id(class_def)]
            except ValueError:
                raise pyamf.ReferenceError, "Reference for class %s not found" % class_def.klass 
Example 49
Project: air-quick-fix   Author: jamesward   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def addService(self, service, name=None, description=None,
        authenticator=None, expose_request=None, preprocessor=None):
        """
        Adds a service to the gateway.

        @param service: The service to add to the gateway.
        @type service: C{callable}, class instance, or a module
        @param name: The name of the service.
        @type name: C{str}
        @raise RemotingError: Service already exists.
        @raise TypeError: C{service} must be C{callable} or a module.
        """
        if isinstance(service, (int, long, float, basestring)):
            raise TypeError, "service cannot be a scalar value"

        allowed_types = (types.ModuleType, types.FunctionType, types.DictType,
            types.MethodType, types.InstanceType, types.ObjectType)

        if not callable(service) and not isinstance(service, allowed_types):
            raise TypeError, "service must be callable, a module, or an object"

        if name is None:
            # TODO: include the module in the name
            if isinstance(service, (type, types.ClassType)):
                name = service.__name__
            elif isinstance(service, types.FunctionType):
                name = service.func_name
            elif isinstance(service, types.ModuleType):
                name = service.__name__
            else:
                name = str(service)

        if name in self.services:
            raise remoting.RemotingError, "Service %s already exists" % name

        self.services[name] = ServiceWrapper(service, description,
            authenticator, expose_request, preprocessor) 
Example 50
Project: ble5-nrf52-mac   Author: tomasero   File: parameterized.py    MIT License 5 votes vote down vote up
def __call__(self, test_func):
        self.assert_not_in_testcase_subclass()

        @wraps(test_func)
        def wrapper(test_self=None):
            test_cls = test_self and type(test_self)
            if test_self is not None:
                if issubclass(test_cls, InstanceType):
                    raise TypeError((
                        "@parameterized can't be used with old-style classes, but "
                        "%r has an old-style class. Consider using a new-style "
                        "class, or '@parameterized.expand' "
                        "(see http://stackoverflow.com/q/54867/71522 for more "
                        "information on old-style classes)."
                    ) %(test_self, ))

            original_doc = wrapper.__doc__
            for num, args in enumerate(wrapper.parameterized_input):
                p = param.from_decorator(args)
                unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
                try:
                    wrapper.__doc__ = nose_tuple[0].__doc__
                    # Nose uses `getattr(instance, test_func.__name__)` to get
                    # a method bound to the test instance (as opposed to a
                    # method bound to the instance of the class created when
                    # tests were being enumerated). Set a value here to make
                    # sure nose can get the correct test method.
                    if test_self is not None:
                        setattr(test_cls, test_func.__name__, unbound_func)
                    yield nose_tuple
                finally:
                    if test_self is not None:
                        delattr(test_cls, test_func.__name__)
                    wrapper.__doc__ = original_doc
        wrapper.parameterized_input = self.get_input()
        wrapper.parameterized_func = test_func
        test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
        return wrapper