Python types.InstanceType() Examples

The following are 30 code examples of types.InstanceType(). 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 types , or try the search function .
Example #1
Source File: rebuild.py    From learn_python3_spider with MIT License 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 #2
Source File: _base.py    From misp42splunk with GNU Lesser General Public License v3.0 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 #3
Source File: __init__.py    From razzy-spinner with 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 #4
Source File: USBIP.py    From PythonUSBIP with 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 #5
Source File: _base.py    From linter-pylama with 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 #6
Source File: USBIP.py    From PythonUSBIP with 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 #7
Source File: visitor.py    From yamdwe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def call_internal(self, func_modifier, args, kw):
        """ Common utility class for calling an overloaded method,
        either bound on a class or not.  func_modifier is a lambda
        function which is used to "bind" bound methods to the correct
        instance
        """
        argtype = type(args[0])
        class Old:
            pass
        if argtype is types.InstanceType: # old-style class
            argtype = args[0].__class__        
        hier = list(inspect.getmro(argtype)) # class hierarchy
        hier.reverse() # order w/ superclass first
        hier = [ t for t in hier if t in self.registry ]
        if len(hier) == 0:
            raise TypeError("Function %s has no compatible overloads registered for argument type %s" % 
                            (self.func_name, argtype))            
        result = None
        for t in hier:
            if not self.allow_cascade[t] and t != hier[-1]:
                continue # don't "cascade" down from superclass on this method
            result = func_modifier(self.registry[t])(*args, **kw)
        return result 
Example #8
Source File: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def try_serialize_handler(handler):
  """Try to serialize map/reduce handler.

  Args:
    handler: handler function/instance. Handler can be a function or an
      instance of a callable class. In the latter case, the handler will
      be serialized across slices to allow users to save states.

  Returns:
    serialized handler string or None.
  """
  if (isinstance(handler, types.InstanceType) or  # old style class
      (isinstance(handler, object) and  # new style class
       not inspect.isfunction(handler) and
       not inspect.ismethod(handler)) and
      hasattr(handler, "__call__")):
    return pickle.dumps(handler)
  return None 
Example #9
Source File: util.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def try_serialize_handler(handler):
  """Try to serialize map/reduce handler.

  Args:
    handler: handler function/instance. Handler can be a function or an
      instance of a callable class. In the latter case, the handler will
      be serialized across slices to allow users to save states.

  Returns:
    serialized handler string or None.
  """
  if (isinstance(handler, types.InstanceType) or  # old style class
      (isinstance(handler, object) and  # new style class
       not inspect.isfunction(handler) and
       not inspect.ismethod(handler)) and
      hasattr(handler, "__call__")):
    return pickle.dumps(handler)
  return None 
Example #10
Source File: c_spec.py    From Computable with 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 #11
Source File: traitlets.py    From Computable with 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 #12
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name) 
Example #13
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name) 
Example #14
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name) 
Example #15
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name) 
Example #16
Source File: rebuild.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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.im_self is None:
                return getattr(anObject.im_class, anObject.__name__)
            else:
                return getattr(anObject.im_self, anObject.__name__)
        elif t == types.InstanceType:
            # Kick it, if it's out of date.
            getattr(anObject, 'nothing', None)
            return anObject
        elif t == types.ClassType:
            return latestClass(anObject)
        else:
            log.msg('warning returning anObject!')
            return anObject 
Example #17
Source File: ensight.py    From pizza with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,data):
    self.change = 0
    self.maxtype = 0
    self.data = data
    if type(data) is types.InstanceType and ".dump" in str(data.__class__):
      self.which = 0
    elif type(data) is types.InstanceType and ".data" in str(data.__class__):
      self.which = 0
    elif type(data) is types.InstanceType and ".mdump" in str(data.__class__):
      self.which = 1
    elif type(data) is types.InstanceType and ".cdata" in str(data.__class__):
      self.which = 1
    else:
      raise StandardError,"unrecognized object passed to ensight"
    
  # -------------------------------------------------------------------- 
Example #18
Source File: oinspect.py    From Computable with 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 #19
Source File: representer.py    From Safejumper-for-Desktop with GNU General Public License v2.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 #20
Source File: dis.py    From oss-ftp with 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 #21
Source File: parameterized.py    From Mastering-Elasticsearch-7.0 with 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 #22
Source File: representer.py    From misp42splunk with 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 #23
Source File: Util.py    From pivy with ISC License 5 votes vote down vote up
def is_String(obj):
            t = type(obj)
            return t is StringType \
                or (t is InstanceType and isinstance(obj, UserString)) 
Example #24
Source File: Util.py    From pivy with ISC License 5 votes vote down vote up
def is_String(obj):
            t = type(obj)
            return t is StringType \
                or t is UnicodeType \
                or (t is InstanceType and isinstance(obj, UserString)) 
Example #25
Source File: Util.py    From pivy with ISC License 5 votes vote down vote up
def is_Sequence(obj):
        t = type(obj)
        return t is ListType \
            or t is TupleType \
            or (t is InstanceType and isinstance(obj, UserList)) 
Example #26
Source File: test_dbshelve.py    From oss-ftp with MIT License 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 #27
Source File: pydoc.py    From oss-ftp with 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 #28
Source File: parameterized.py    From recruit with 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 #29
Source File: Util.py    From pivy with ISC License 5 votes vote down vote up
def is_List(obj):
        t = type(obj)
        return t is ListType \
            or (t is InstanceType and isinstance(obj, UserList)) 
Example #30
Source File: rpc.py    From oss-ftp with MIT License 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)