Python types.ObjectType() Examples

The following are code examples for showing how to use types.ObjectType(). 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: pyglet   Author: pyglet   File: yacc.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def lr_read_tables(module=tab_module,optimize=0):
    global _lr_action, _lr_goto, _lr_productions, _lr_method
    try:
        exec("import %s as parsetab" % module)
        global parsetab  # declare the name of the imported module

        if (optimize) or (Signature.digest() == parsetab._lr_signature):
            _lr_action = parsetab._lr_action
            _lr_goto   = parsetab._lr_goto
            _lr_productions = parsetab._lr_productions
            _lr_method = parsetab._lr_method
            return 1
        else:
            return 0

    except (ImportError,AttributeError):
        return 0


# Available instance types.  This is used when parsers are defined by a class.
# it's a little funky because I want to preserve backwards compatibility
# with Python 2.0 where types.ObjectType is undefined. 
Example 2
Project: centreon-discovery   Author: Centreon-Community   File: converters.py    GNU General Public License v2.0 5 votes vote down vote up
def Instance2Str(o, d):

    """

    Convert an Instance to a string representation.  If the __str__()
    method produces acceptable output, then you don't need to add the
    class to conversions; it will be handled by the default
    converter. If the exact class is not found in d, it will use the
    first class it can find for which o is an instance.

    """

    if d.has_key(o.__class__):
        return d[o.__class__](o, d)
    cl = filter(lambda x,o=o:
                type(x) is types.ClassType
                and isinstance(o, x), d.keys())
    if not cl and hasattr(types, 'ObjectType'):
        cl = filter(lambda x,o=o:
                    type(x) is types.TypeType
                    and isinstance(o, x)
                    and d[x] is not Instance2Str,
                    d.keys())
    if not cl:
        return d[types.StringType](o,d)
    d[o.__class__] = d[cl[0]]
    return d[cl[0]](o, d) 
Example 3
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 4
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 5
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 6
Project: air-quick-fix   Author: jamesward   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_mro(C):
    """
    Compute the class precedence list (mro)
    """
    def merge(seqs):
        res = []
        i = 0

        while 1:
            nonemptyseqs = [seq for seq in seqs if seq]
            if not nonemptyseqs:
                return res

            i += 1
            for seq in nonemptyseqs:
                cand = seq[0]
                nothead = [s for s in nonemptyseqs if cand in s[1:]]

                if nothead:
                    cand = None
                else:
                    break

            if not cand:
                raise NameError, "Inconsistent hierarchy"

            res.append(cand)

            for seq in nonemptyseqs:
                if seq[0] == cand:
                    del seq[0]

    if not isinstance(C, (types.ClassType, types.ObjectType)):
        raise TypeError, 'class type expected'

    if hasattr(C, '__mro__'):
        return C.__mro__

    return merge([[C]] + map(get_mro, C.__bases__) + [list(C.__bases__)]) 
Example 7
Project: daf-recipes   Author: italia   File: toolkit_sphinx_extension.py    GNU General Public License v3.0 5 votes vote down vote up
def source_read(app, docname, source):
    '''Transform the contents of plugins-toolkit.rst to contain reference docs.

    '''
    # We're only interested in the 'plugins-toolkit' doc (plugins-toolkit.rst).
    if docname != 'extensions/plugins-toolkit':
        return

    source_ = ''
    for name, thing in inspect.getmembers(toolkit):

        # The plugins toolkit can override the docstrings of some of its
        # members (e.g. things that are imported from third-party libraries)
        # by putting custom docstrings in this docstring_overrides dict.
        custom_docstring = toolkit.docstring_overrides.get(name)

        if inspect.isfunction(thing):
            source_ += format_function(name, thing, docstring=custom_docstring)
        elif inspect.ismethod(thing):
            # We document plugins toolkit methods as if they're functions. This
            # is correct because the class ckan.plugins.toolkit._Toolkit
            # actually masquerades as a module ckan.plugins.toolkit, and you
            # call its methods as if they were functions.
            source_ += format_function(name, thing, docstring=custom_docstring)
        elif inspect.isclass(thing):
            source_ += format_class(name, thing, docstring=custom_docstring)
        elif isinstance(thing, types.ObjectType):
            source_ += format_object(name, thing, docstring=custom_docstring)

        else:
            assert False, ("Someone added {name}:{thing} to the plugins "
                           "toolkit and this Sphinx extension doesn't know "
                           "how to document that yet. If you're that someone, "
                           "you need to add a new format_*() function for it "
                           "here or the docs won't build.".format(
                               name=name, thing=thing))

    source[0] += source_

    # This is useful for debugging the generated RST.
    #open('/tmp/source', 'w').write(source[0]) 
Example 8
Project: pyebpf   Author: dany74q   File: helpers.py    MIT License 5 votes vote down vote up
def assert_type(expected_type, **kwargs):
    # type: (types.TypeType|types.TupleType[types.TypeType], **types.ObjectType) -> None

    for k, v in kwargs.iteritems():
        assert isinstance(v, expected_type), 'Expected {} to be of type {}, actually got {}'.format(k,
                                                                                                    expected_type,
                                                                                                    type(v)) 
Example 9
Project: pyebpf   Author: dany74q   File: ebpf_wrapper.py    MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        # type: (**types.ObjectType) -> None

        self._attached_kprobes = {}

        log_level = kwargs.get('log_level', logging.INFO)
        self.logger.setLevel(log_level)

        if kwargs:
            self.logger.debug('Arguments were passed during init - will instantiate parent')
            super(EBPFWrapper, self).__init__(**kwargs)
        else:
            super(EBPFWrapper, self).__init__(text=self._DUMMY_PROGRAM) 
Example 10
Project: Project-Altis-Copyright-Proof-Source   Author: CodeAnGo   File: ToonPythonUtil.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, instanceOrClass):
        if type(instanceOrClass) in (types.ClassType, types.TypeType):
            cls = instanceOrClass
        else:
            cls = instanceOrClass.__class__
        self._cls = cls
        self._bases = []
        for base in self._cls.__bases__:
            if base not in (types.ObjectType, types.TypeType):
                self._bases.append(ClassTree(base)) 
Example 11
Project: insteon-terminal   Author: pfrommerd   File: console_commands.py    The Unlicense 5 votes vote down vote up
def help(obj = None):
	"""help(object) prints out help for object, e.g. help(modem)"""
	if obj is not None :
		sep='\n'
		if isinstance(obj, (types.FunctionType)):
			if obj.__doc__ is None :
				iofun.out("No documentation for \"" +
						obj.__name__ + "\"")
				return

			iofun.out(obj.__doc__)
		elif isinstance(obj, (types.ClassType, types.ObjectType)):
			if obj.__doc__ is None :
				iofun.out("No documentation for \"" +
					  	obj.__class__.__name__ + "\"")
				return
			iofun.out(obj.__doc__)
			docList = [getattr(obj, method).__doc__ for method in dir(obj) if callable(getattr(obj, method)) and getattr(obj, method).__doc__]
			if len(docList) == 0:
				return
			maxMethodLen = max([len(doc.split(sep)[0]) for doc in docList])
			iofun.out("\n".join(["%s %s" %
								 (doc.split(sep)[0].ljust(maxMethodLen + 1),
								  " ".join(doc.split(sep)[1:]).strip())
								 for doc in docList]))
	else:
		out("-------Welcome to the Insteon Terminal-------")
		out("to get a list of available functions, type '?'")
		out("to get help, type help(funcName) or help(objectName)")
		out("for example: help(Modem2413U)")
		out("to quit, type 'quit()'") 
Example 12
Project: open-data-beer-sheva   Author: Smart7br7   File: toolkit_sphinx_extension.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def source_read(app, docname, source):
    '''Transform the contents of plugins-toolkit.rst to contain reference docs.

    '''
    # We're only interested in the 'plugins-toolkit' doc (plugins-toolkit.rst).
    if docname != 'extensions/plugins-toolkit':
        return

    source_ = ''
    for name, thing in inspect.getmembers(toolkit):

        # The plugins toolkit can override the docstrings of some of its
        # members (e.g. things that are imported from third-party libraries)
        # by putting custom docstrings in this docstring_overrides dict.
        custom_docstring = toolkit.docstring_overrides.get(name)

        if inspect.isfunction(thing):
            source_ += format_function(name, thing, docstring=custom_docstring)
        elif inspect.ismethod(thing):
            # We document plugins toolkit methods as if they're functions. This
            # is correct because the class ckan.plugins.toolkit._Toolkit
            # actually masquerades as a module ckan.plugins.toolkit, and you
            # call its methods as if they were functions.
            source_ += format_function(name, thing, docstring=custom_docstring)
        elif inspect.isclass(thing):
            source_ += format_class(name, thing, docstring=custom_docstring)
        elif isinstance(thing, types.ObjectType):
            source_ += format_object(name, thing, docstring=custom_docstring)

        else:
            assert False, ("Someone added {name}:{thing} to the plugins "
                           "toolkit and this Sphinx extension doesn't know "
                           "how to document that yet. If you're that someone, "
                           "you need to add a new format_*() function for it "
                           "here or the docs won't build.".format(
                               name=name, thing=thing))

    source[0] += source_

    # This is useful for debugging the generated RST.
    #open('/tmp/source', 'w').write(source[0]) 
Example 13
Project: MetaPlot   Author: MetaPlot   File: mplintercept.py    MIT License 5 votes vote down vote up
def attach_decorators_to_object(obj):
    recursive_names = []
    #~ recursive_names = ['canvas']
    # canvas causes problem with exit not being able to disconnect

    for name, fn in inspect.getmembers(obj):
        if isinstance(fn, types.UnboundMethodType):
            # fn is original method of obj
            new_method = intercept_method(obj, fn)
            # now override so that the decorator will always be called
            setattr(obj, name, new_method)
        elif isinstance(fn, types.ObjectType) and name in recursive_names:
            # recursively call this functiona gain
            attach_decorators_to_object(fn) 
Example 14
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: deferred.py    Apache License 2.0 5 votes vote down vote up
def _curry_callable(obj, *args, **kwargs):
  """Takes a callable and arguments and returns a task queue tuple.

  The returned tuple consists of (callable, args, kwargs), and can be pickled
  and unpickled safely.

  Args:
    obj: The callable to curry. See the module docstring for restrictions.
    args: Positional arguments to call the callable with.
    kwargs: Keyword arguments to call the callable with.
  Returns:
    A tuple consisting of (callable, args, kwargs) that can be evaluated by
    run() with equivalent effect of executing the function directly.
  Raises:
    ValueError: If the passed in object is not of a valid callable type.
  """
  if isinstance(obj, types.MethodType):
    return (invoke_member, (obj.im_self, obj.im_func.__name__) + args, kwargs)
  elif isinstance(obj, types.BuiltinMethodType):
    if not obj.__self__:

      return (obj, args, kwargs)
    else:
      return (invoke_member, (obj.__self__, obj.__name__) + args, kwargs)
  elif isinstance(obj, types.ObjectType) and hasattr(obj, "__call__"):
    return (obj, args, kwargs)
  elif isinstance(obj, (types.FunctionType, types.BuiltinFunctionType,
                        types.ClassType, types.UnboundMethodType)):
    return (obj, args, kwargs)
  else:
    raise ValueError("obj must be callable") 
Example 15
Project: doc-topic-coherence   Author: dkorenci   File: IdComposer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def deduceId(obj):
    ''' Return obj.id if .id exists, else deduce an approximation for id,
            ie name of the class or function. '''
    import types
    if obj == None: return None
    if hasattr(obj, 'id'): return obj.id
    else:
        if isinstance(obj, types.FunctionType): return obj.__name__
        elif isinstance(obj, types.ClassType): return obj.__name__
        elif isinstance(obj, types.ObjectType): return obj.__class__.__name__
        else: return str(obj) 
Example 16
Project: pale   Author: Loudr   File: resource.py    MIT License 5 votes vote down vote up
def __init__(self, doc_string, item_type, **kwargs):
        kwargs['doc_string'] = doc_string
        super(ResourceList, self).__init__(**kwargs)

        if isinstance(item_type, Resource):
            self._item_resource = item_type
        if isinstance(item_type, types.ObjectType):
            self._item_resource = item_type()
        else:
            raise ValueError("""Failed to initialize ResourceList, since it
            was passed an `item_type` other than an Instance of a Resource or
            a Resource class.""")
        self._description = "A list of %s Resources" % self._item_resource.name 
Example 17
Project: Tinychat-Bot--Discontinued   Author: Tinychat   File: __init__.py    MIT License 4 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 pyamf.remoting.RemotingError: Service already exists.
        @raise TypeError: C{service} cannot be a scalar value.
        @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 python.callable(service) and \
                not isinstance(service, allowed_types):
            raise TypeError("Service must be a callable, 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 18
Project: budoc   Author: zeaphoo   File: pydoc.py    MIT License 4 votes vote down vote up
def params(self):
        """
        Returns a list where each element is a nicely formatted
        parameter of this function. This includes argument lists,
        keyword arguments and default values.
        """
        def fmt_param(el):
            if isinstance(el, str) or isinstance(el, unicode):
                return el
            else:
                return '(%s)' % (', '.join(map(fmt_param, el)))
        try:
            getspec = getattr(inspect, 'getfullargspec', inspect.getargspec)
            s = getspec(self.func)
        except TypeError:
            # I guess this is for C builtin functions?
            return ['...']

        params = []
        for i, param in enumerate(s.args):
            if param.lower() == 'self':
                continue
            if s.defaults is not None and len(s.args) - i <= len(s.defaults):
                defind = len(s.defaults) - (len(s.args) - i)
                default_value = s.defaults[defind]
                value = repr(default_value).strip()
                if value[0] == '<' and value[-1] == '>':
                    if type(default_value) == types.TypeType:
                        value = default_value.__name__
                    elif type(default_value) == types.ObjectType:
                        value = '%s()'%(default_value.__class__.__name__)
                params.append('%s=%s' % (param, value))
            else:
                params.append(fmt_param(param))
        if s.varargs is not None:
            params.append('*%s' % s.varargs)

        # TODO: This needs to be adjusted in Python 3. There's more stuff
        #       returned from getfullargspec than what we're looking at here.
        keywords = getattr(s, 'varkw', getattr(s, 'keywords', None))
        if keywords is not None:
            params.append('**%s' % keywords)
        return params 
Example 19
Project: pyebpf   Author: dany74q   File: ebpf_wrapper.py    MIT License 4 votes vote down vote up
def attach_kprobe(self, event, fn=None, implicitly_add_syscall_args=True, **kwargs):
        # type: (types.StringTypes, types.FunctionType, types.BooleanType, **types.ObjectType) -> None
        """
        Attaches a kernel probe to a given python function

        :param event: Name of the event to attach to
        :param fn: Python function to invoke
        :param implicitly_add_syscall_args: If True, will try to implicitly generate the syscall arguments,
                                            copying them from our ebpf routine back to user-space
        """
        assert_type(types.StringTypes, event=event)
        if fn is not None:
            assert_type(types.FunctionType, fn=fn)

        event = normalize_event(event)
        attached_kprobe_descriptor = None

        try:
            if not fn:
                self.logger.debug('Function was not passed - fallbacking to default implementation')
                attached_kprobe_descriptor = AttachedKProbeDescriptor(event, self)
                return super(EBPFWrapper, self).attach_kprobe(event, **kwargs)

            event_without_syscall_prefix = None

            # noinspection PyUnresolvedReferences
            for syscall_prefix in self._syscall_prefixes:
                syscall_prefix = syscall_prefix.lower()
                if event.startswith(syscall_prefix) or \
                        event.startswith(self.KRPOBE_EVENT_SYSCALL_PREFIX + syscall_prefix):
                    event_without_syscall_prefix = event \
                        .replace(syscall_prefix, '') \
                        .replace(self.KRPOBE_EVENT_SYSCALL_PREFIX, '')
                    break

            if event_without_syscall_prefix is None:
                self.logger.debug('Event is not prefixed with a known syscall prefix - '
                                  'fallbacking to default implementation')
                attached_kprobe_descriptor = AttachedKProbeDescriptor(event, self)
                return super(EBPFWrapper, self).attach_kprobe(event, **kwargs)

            event_without_syscall_prefix = self._replace_event_alias_if_needed(event_without_syscall_prefix)
            attached_kprobe_descriptor = self._attach_kprobe_with_managed_polling_thread(event,
                                                                                         event_without_syscall_prefix,
                                                                                         fn,
                                                                                         implicitly_add_syscall_args)
        finally:
            if attached_kprobe_descriptor is not None:
                self._attached_kprobes.setdefault(event, []).append(attached_kprobe_descriptor)