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: 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 #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: 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 #9
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def constructor(cls, callable):
        '''Return a closure that constructs the original `callable` type from a function.'''

        # `callable` is a function type, so just return a closure that returns it
        if isinstance(callable, types.FunctionType):
            return lambda func: func

        # if it's a method type, then we just need to extract the related properties to construct it
        elif isinstance(callable, types.MethodType):
            return lambda method, self=callable.im_self, cls=callable.im_class: types.MethodType(method, self, cls)

        # if it's a property decorator, we just need to pass the function as an argument to the decorator
        elif isinstance(callable, (staticmethod, classmethod)):
            return lambda method, mt=callable.__class__: mt(method)

        # if it's a method instance, then we just need to instantiate it so that it's bound
        elif isinstance(callable, types.InstanceType):
            return lambda method, mt=callable.__class__: types.InstanceType(mt, dict(method.__dict__))

        # otherwise if it's a class or a type, then we just need to create the object with its bases
        elif isinstance(n, (types.TypeType, types.ClassType)):
            return lambda method, t=callable.__class__, name=callable.__name__, bases=callable.__bases__: t(name, bases, dict(method.__dict__))

        # if we get here, then we have no idea what kind of type `callable` is
        raise internal.exceptions.InvalidTypeOrValueError(callable.__class__)

### function decorator for translating arguments belonging to a function 
Example #10
Source File: numerictypes.py    From Splunking-Crime with GNU Affero 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 #11
Source File: optparse.py    From Splunking-Crime with GNU Affero General Public License v3.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 #12
Source File: jelly.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _unjelly_class(self, rest):
        clist = rest[0].split('.')
        modName = '.'.join(clist[:-1])
        if not self.taster.isModuleAllowed(modName):
            raise InsecureJelly("module %s not allowed" % modName)
        klaus = namedObject(rest[0])
        objType = type(klaus)
        if objType not in (types.ClassType, types.TypeType):
            raise InsecureJelly(
                "class %r unjellied to something that isn't a class: %r" % (
                    rest[0], klaus))
        if not self.taster.isClassAllowed(klaus):
            raise InsecureJelly("class not allowed: %s" % qual(klaus))
        return klaus 
Example #13
Source File: optparse.py    From medicare-demo 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 #14
Source File: numerictypes.py    From elasticintel 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 #15
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prototype(cls, func, parameters={}):
        '''Generate a prototype for an instance of a function.'''
        args, defaults, (star, starstar) = cls.ex_args(func)
        argsiter = ("{:s}={:s}".format(n, parameters[n].__name__ if isinstance(parameters[n], types.TypeType) or parameters[n] in {callable} else '|'.join(t.__name__ for t in parameters[n]) if hasattr(parameters[n], '__iter__') else "{!r}".format(parameters[n])) if parameters.has_key(n) else n for n in args)
        res = (argsiter, ("*{:s}".format(star),) if star else (), ("**{:s}".format(starstar),) if starstar else ())
        return "{:s}({:s})".format(func.func_name, ', '.join(itertools.chain(*res))) 
Example #16
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reconstructor(cls, n):
        '''Return a closure that returns the original callable type for a function.'''
        if isinstance(n, types.FunctionType):
            return lambda f: f
        if isinstance(n, types.MethodType):
            return lambda f: types.MethodType(f, n.im_self, n.im_class)
        if isinstance(n, (staticmethod, classmethod)):
            return lambda f: type(n)(f)
        if isinstance(n, types.InstanceType):
            return lambda f: types.InstanceType(type(n), dict(f.__dict__))
        if isinstance(n, (types.TypeType, types.ClassType)):
            return lambda f: type(n)(n.__name__, n.__bases__, dict(f.__dict__))
        raise internal.exceptions.InvalidTypeOrValueError(type(n)) 
Example #17
Source File: casc_plugin.py    From CASC with GNU General Public License v2.0 5 votes vote down vote up
def get_parser():
    proc, bits = get_architecture()
    mapping = {'intel' : IntelParser}

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

        return parser(bits)

    return CASCParser(bits) 
Example #18
Source File: optparse.py    From CTFCrackTools-V2 with GNU General Public License v3.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 #19
Source File: optparse.py    From CTFCrackTools-V2 with GNU General Public License v3.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 #20
Source File: optparse.py    From RevitBatchProcessor with GNU General Public License v3.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 #21
Source File: pycmp.py    From pywbem with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_modinfos_from_sym_dict(sym_dict, abs_modname, mod_file):

    if not isinstance(sym_dict, dict):
        raise TypeError("sym_dict parameter must be a dict object.")

    all_symbols = sym_dict.keys()
    exp_symbols = sym_dict.get('__all__', all_symbols)

    unexpected_symbols = set(exp_symbols) - set(all_symbols)
    assert len(unexpected_symbols) == 0, "module %s has unexpected exported symbols: %r" %  sorted(unexpected_symbols)

    modinfos = {}
    mi = {}
    mi['name'] = abs_modname
    mi['file'] = mod_file
    syminfos = {}
    for sym in all_symbols:
        si = {}
        si['name'] = sym
        sym_obj = sym_dict[sym]
        if isinstance(sym_obj, types.ClassType):
            tn = 'old-style class'
        elif not hasattr(sym_obj, '__module__'):
            # e.g. tuple
            tn = type(sym_obj).__name__
        elif sym_obj.__module__ == '__builtin__':
            tn = type(sym_obj).__name__
        elif isinstance(sym_obj, types.TypeType):
            tn = 'new-style class'
        else:
            tn = type(sym_obj).__name__
        si['typename'] = tn
        si['modname'] = getattr(sym_obj, '__module__', None)
        si['exported'] = bool(sym in exp_symbols)
        syminfos[sym] = si
    mi['syminfos'] = syminfos
    modinfos[abs_modname] = mi

    return modinfos 
Example #22
Source File: xmlmanager.py    From canvas with BSD 3-Clause "New" or "Revised" 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) == types.ListType:
                        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) 
Example #23
Source File: optparse.py    From PokemonGo-DesktopMap 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 #24
Source File: optparse.py    From unity-python 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 #25
Source File: optparse.py    From canape with GNU General Public License v3.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 #26
Source File: optparse.py    From CTFCrackTools with GNU General Public License v3.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 #27
Source File: optparse.py    From CTFCrackTools with GNU General Public License v3.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 #28
Source File: numerictypes.py    From keras-lambda 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 #29
Source File: numerictypes.py    From ImageFusion 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 #30
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)