Python types.TypeType() Examples

The following are 30 code examples of types.TypeType(). 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: casc_plugin.py    From CASC with GNU General Public License v2.0 6 votes vote down vote up
def get_gui():
    proc, bits = get_architecture()
    mapping = {'intel' : IntelMask}

    if proc in mapping:
        gui = mapping[proc]
        if type(gui) != types.TypeType:
            #   For future use if mapping includes more of a breakdown
            return CASCMask(bits)

        return gui(bits)

    return CASCMask(bits)


#   Create ClamAV icon 
Example #2
Source File: ExperimentFactory.py    From pilot with Apache License 2.0 6 votes vote down vote up
def newExperiment(self, experiment):
        """ Generate a new site information object """

        # get all classes
        experimentClasses = [j for (i,j) in globals().iteritems() if isinstance(j, TypeType) and issubclass(j, Experiment)]

        # loop over all subclasses
        for experimentClass in experimentClasses:
            si = experimentClass()

            # return the matching experiment class
            if si.getExperiment() == experiment:
                return experimentClass

        # if no class was found, raise an error
        raise ValueError('ExperimentFactory: No such class: "%s"' % (experiment)) 
Example #3
Source File: SiteInformationFactory.py    From pilot with Apache License 2.0 6 votes vote down vote up
def newSiteInformation(self, experiment):
        """ Generate a new site information object """

        # get all classes
        siteInformationClasses = [j for (i,j) in globals().iteritems() if isinstance(j, TypeType) and issubclass(j, SiteInformation)]

        # loop over all subclasses
        for siteInformationClass in siteInformationClasses:
            si = siteInformationClass()

            # return the matching experiment class
            if si.getExperiment() == experiment:
                return siteInformationClass

        # if no class was found, raise an error
        raise ValueError('SiteInformationFactory: No such class: "%s"' % (experiment)) 
Example #4
Source File: RunJobFactory.py    From pilot with Apache License 2.0 6 votes vote down vote up
def newRunJob(self, _type="generic"):
        """ Generate a new site information object """



        # get all classes
        runJobClasses = [j for (i,j) in globals().iteritems() if isinstance(j, TypeType) and issubclass(j, RunJob)]
        
        # loop over all subclasses
        for runJobClass in runJobClasses:
            si = runJobClass()

            # return the matching RunJob class
            if si.getRunJob() == _type:
                return runJobClass

        # if no class was found, raise an error
        raise ValueError('RunJobFactory: No such class: "%s"' % (_type)) 
Example #5
Source File: EventServiceFactory.py    From pilot with Apache License 2.0 6 votes vote down vote up
def newEventService(self, experiment):
        """ Generate a new site information object """

        # get all classes
        eventServiceClasses = [j for (i,j) in globals().iteritems() if isinstance(j, TypeType) and issubclass(j, EventService)]
        print eventServiceClasses
        # loop over all subclasses

        if experiment == "Nordugrid-ATLAS":
            experiment = "ATLAS"
        for eventServiceClass in eventServiceClasses:
            si = eventServiceClass()

            # return the matching eventService class
            if si.getEventService() == experiment:
                return eventServiceClass

        # if no class was found, raise an error
        raise ValueError('EventServiceFactory: No such class: "%s"' % (eventServiceClass)) 
Example #6
Source File: components.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def removeComponent(self, component):
        """
        Remove the given component from me entirely, for all interfaces for which
        it has been registered.

        @return: a list of the interfaces that were removed.
        """
        if (isinstance(component, types.ClassType) or
            isinstance(component, types.TypeType)):
            warnings.warn("passing interface to removeComponent, you probably want unsetComponent", DeprecationWarning, 1)
            self.unsetComponent(component)
            return [component]
        l = []
        for k, v in self._adapterCache.items():
            if v is component:
                del self._adapterCache[k]
                l.append(reflect.namedObject(k))
        return l 
Example #7
Source File: utils.py    From airbrake-python with MIT License 6 votes vote down vote up
def is_exc_info_tuple(exc_info):
    """Determine whether 'exc_info' is an exc_info tuple.

    Note: exc_info tuple means a tuple of exception related values
    as returned by sys.exc_info().
    """
    try:
        errtype, value, tback = exc_info
        if all([x is None for x in exc_info]):
            return True
        elif all((isinstance(errtype, TypeType),
                  isinstance(value, Exception),
                  hasattr(tback, 'tb_frame'),
                  hasattr(tback, 'tb_lineno'),
                  hasattr(tback, 'tb_next'))):
            return True
    except (TypeError, ValueError):
        pass
    return False 
Example #8
Source File: SparseArray.py    From biskit with GNU General Public License v3.0 6 votes vote down vote up
def isType( o, t ):
    """
    Test for correct type or correct class::
      isType( o, type_or_class ) -> 1|0

    @param o: object to test
    @type  o: any
    @param t: type OR class
    @type  t: any
    @return: result of test
    @rtype: 1|0
    """
    tt = type(o)
    if tt == types.TypeType:
        return type( o ) == t
    if tt == types.ClassType:
        return isinstance( o, t )
    raise Exception, 'unsupported argument type: %s.' % str(tt)


## to be transferred into Biskit.tools 
Example #9
Source File: optparse.py    From meddle with MIT License 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #10
Source File: optparse.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #11
Source File: numerictypes.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def _python_type(t):
        """returns the type corresponding to a certain Python type"""
        if not isinstance(t, _types.TypeType):
            t = type(t)
        return allTypes[_python_types.get(t, 'object_')] 
Example #12
Source File: pyversion.py    From locality-sensitive-hashing with MIT License 5 votes vote down vote up
def sort_list(l, key, reverse=False):
        return l.sort(key=key, reverse=reverse)

# In Python 3.x, all objects are "new style" objects descended from 'type', and
# thus types.ClassType and types.TypeType don't exist anymore.  For
# compatibility, we make sure they still work. 
Example #13
Source File: optparse.py    From BinderFilter with MIT License 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #14
Source File: numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def _python_type(t):
        """returns the type corresponding to a certain Python type"""
        if not isinstance(t, _types.TypeType):
            t = type(t)
        return allTypes[_python_types.get(t, 'object_')] 
Example #15
Source File: wildcard.py    From Computable with MIT License 5 votes vote down vote up
def is_type(obj, typestr_or_type):
    """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
    can take strings or actual python types for the second argument, i.e.
    'tuple'<->TupleType. 'all' matches all types.

    TODO: Should be extended for choosing more than one type."""
    if typestr_or_type == "all":
        return True
    if type(typestr_or_type) == types.TypeType:
        test_type = typestr_or_type
    else:
        test_type = typestr2type.get(typestr_or_type, False)
    if test_type:
        return isinstance(obj, test_type)
    return False 
Example #16
Source File: optparse.py    From Computable with MIT License 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #17
Source File: pyversion.py    From Computable with MIT License 5 votes vote down vote up
def sort_list(l, key, reverse=False):
        return l.sort(key=key, reverse=reverse)

# In Python 3.x, all objects are "new style" objects descended from 'type', and
# thus types.ClassType and types.TypeType don't exist anymore.  For
# compatibility, we make sure they still work. 
Example #18
Source File: optparse.py    From oss-ftp with MIT License 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #19
Source File: inspect_utils.py    From g3ar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_classes(mod, metaclass=None):
    """"""
    if metaclass == None:
        metaclass = tuple([types.TypeType, types.ClassType])
    for i in get_callables(mod):
        if isinstance(i, metaclass):
            yield i 
Example #20
Source File: inspect_utils.py    From g3ar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_classes(mod, metaclass=None):
    """"""
    if metaclass == None:
        metaclass = tuple([types.TypeType, types.ClassType])
    for i in get_callables(mod):
        if isinstance(i, metaclass):
            yield i 
Example #21
Source File: optparse.py    From hacker-scripts with MIT License 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #22
Source File: optparse.py    From hacker-scripts with MIT License 5 votes vote down vote up
def _check_type(self):
        if self.type is None:
            if self.action in self.ALWAYS_TYPED_ACTIONS:
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
            # complicated check of __builtin__ is only necessary for
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
            import __builtin__
            if ( type(self.type) is types.TypeType or
                 (hasattr(self.type, "__name__") and
                  getattr(__builtin__, self.type.__name__, None) is self.type) ):
                self.type = self.type.__name__

            if self.type == "str":
                self.type = "string"

            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self) 
Example #23
Source File: markdown.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def md_class(class_obj):
  """Write markdown documentation for a class.

  Documents public methods. Does not currently document subclasses.

  Args:
    class_obj: a types.TypeType object for the class that should be
      documented.
  Returns:
    A list of markdown-formatted lines.
  """
  content = [md_heading(md_escape(class_obj.__name__), level=2)]
  content.append('')
  if class_obj.__doc__:
    content.extend(md_docstring(class_obj.__doc__))

  def should_doc(name, obj):
    return (isinstance(obj, types.FunctionType)
            and (name.startswith('__') or not name.startswith('_')))

  methods_to_doc = sorted(
      obj for name, obj in class_obj.__dict__.iteritems()
      if should_doc(name, obj))

  for m in methods_to_doc:
    content.extend(md_function(m, class_obj=class_obj))

  return content 
Example #24
Source File: markdown.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def md_class(class_obj):
  """Write markdown documentation for a class.

  Documents public methods. Does not currently document subclasses.

  Args:
    class_obj: a types.TypeType object for the class that should be
      documented.
  Returns:
    A list of markdown-formatted lines.
  """
  content = [md_heading(md_escape(class_obj.__name__), level=2)]
  content.append('')
  if class_obj.__doc__:
    content.extend(md_docstring(class_obj.__doc__))

  def should_doc(name, obj):
    return (isinstance(obj, types.FunctionType)
            and (name.startswith('__') or not name.startswith('_')))

  methods_to_doc = sorted(
      obj for name, obj in class_obj.__dict__.iteritems()
      if should_doc(name, obj))

  for m in methods_to_doc:
    content.extend(md_function(m, class_obj=class_obj))

  return content 
Example #25
Source File: numerictypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _python_type(t):
        """returns the type corresponding to a certain Python type"""
        if not isinstance(t, _types.TypeType):
            t = type(t)
        return allTypes[_python_types.get(t, 'object_')] 
Example #26
Source File: recipe-576687.py    From code with MIT License 5 votes vote down vote up
def newPizza(ingredient):
        # Walk through all Pizza classes 
        pizzaClasses = [j for (i,j) in globals().iteritems() if isinstance(j, TypeType) and issubclass(j, Pizza)]
        for pizzaClass in pizzaClasses :
            if pizzaClass.containsIngredient(ingredient):
                return pizzaClass()
        #if research was unsuccessful, raise an error
        raise ValueError('No pizza containing "%s".' % ingredient) 
Example #27
Source File: numerictypes.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def _python_type(t):
        """returns the type corresponding to a certain Python type"""
        if not isinstance(t, _types.TypeType):
            t = type(t)
        return allTypes[_python_types.get(t, 'object_')] 
Example #28
Source File: __init__.py    From girlfriend with MIT License 5 votes vote down vote up
def register_entry_points_plugins(entry_point="girlfriend.plugin"):
    """将基于entry_point的第三方插件注册到默认管理器
       :param entry_point: 加载插件的entry_point
    """

    global plugin_manager

    third_party_plugin_mgr = extension.ExtensionManager(
        namespace=entry_point, invoke_on_load=False)

    for ext in third_party_plugin_mgr:
        plugin_object, plugin = ext.plugin, None

        # 插件对象类型
        if isinstance(plugin_object, Plugin):
            plugin = plugin_object

        # 模块类型
        elif isinstance(plugin_object, types.ModuleType):
            plugin = Plugin.wrap_module(plugin_object)

        # 函数类型
        elif isinstance(plugin_object, types.FunctionType):
            plugin = Plugin.wrap_function(
                ext.name, plugin_object.__doc__, plugin_object)

        # 类类型
        elif isinstance(plugin_object, (types.ClassType, types.TypeType)):
            plugin = Plugin.wrap_class(plugin_object)

        # 不被支持的插件类型
        else:
            raise InvalidPluginException(
                u"插件 '{}' 的类型 '{}'不被支持".format(
                    ext.name,
                    type(plugin_object).__name__)
            )

        plugin_manager.register(plugin) 
Example #29
Source File: util.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def usage(obj, selfname='self'):
    import inspect
    str(obj) # In case it's lazy, this will load it.

    if not isinstance(obj, (types.TypeType, types.ClassType)):
        obj = obj.__class__

    print '%s supports the following operations:' % obj.__name__
    for (name, method) in sorted(pydoc.allmethods(obj).items()):
        if name.startswith('_'): continue
        if getattr(method, '__deprecated__', False): continue

        args, varargs, varkw, defaults = inspect.getargspec(method)
        if (args and args[0]=='self' and
            (defaults is None or len(args)>len(defaults))):
            args = args[1:]
            name = '%s.%s' % (selfname, name)
        argspec = inspect.formatargspec(
            args, varargs, varkw, defaults)
        print textwrap.fill('%s%s' % (name, argspec),
                            initial_indent='  - ',
                            subsequent_indent=' '*(len(name)+5))

##########################################################################
# IDLE
########################################################################## 
Example #30
Source File: xmlmanager.py    From aws-extender with MIT License 5 votes vote down vote up
def _build_query(self, cls, filters, limit, order_by):
        import types
        if len(filters) > 4:
            raise Exception('Too many filters, max is 4')
        parts = []
        properties = cls.properties(hidden=False)
        for filter, value in filters:
            name, op = filter.strip().split()
            found = False
            for property in properties:
                if property.name == name:
                    found = True
                    if types.TypeType(value) == list:
                        filter_parts = []
                        for val in value:
                            val = self.encode_value(property, val)
                            filter_parts.append("'%s' %s '%s'" % (name, op, val))
                        parts.append("[%s]" % " OR ".join(filter_parts))
                    else:
                        value = self.encode_value(property, value)
                        parts.append("['%s' %s '%s']" % (name, op, value))
            if not found:
                raise Exception('%s is not a valid field' % name)
        if order_by:
            if order_by.startswith("-"):
                key = order_by[1:]
                type = "desc"
            else:
                key = order_by
                type = "asc"
            parts.append("['%s' starts-with ''] sort '%s' %s" % (key, key, type))
        return ' intersection '.join(parts)