Python types.NoneType() Examples

The following are 30 code examples of types.NoneType(). 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: thutil.py    From Depth-Map-Prediction with GNU General Public License v3.0 6 votes vote down vote up
def breakpoint(output, vars=None, cond=lambda v: True, grad=True):
    tb = tuple(traceback.extract_stack()[:-1])
    py_vars = {}
    if type(vars) not in (tuple, list, dict, types.NoneType):
        raise ValueError('vars keyword arg must be None, dict, list or tuple')
    if not isinstance(vars, dict):
        frame_locals = inspect.stack()[1][0].f_locals
        if vars is not None:
            frame_locals = dict((name, val)
                                for (name, val) in frame_locals.iteritems()
                                if name in vars or val in vars)
        vars = frame_locals
    assert isinstance(vars, dict)
    th_vars = dict((name, val) for (name, val) in vars.iteritems()
                               if isinstance(val, _theano_types))
    py_vars = dict((name, val) for (name, val) in vars.iteritems()
                               if name not in th_vars)
    (th_var_names, th_var_vals) = zip(*th_vars.iteritems())
    return Breakpoint(th_var_names, cond, tb, py_vars, grad) \
                     (output, *th_var_vals) 
Example #2
Source File: utils.py    From backend with GNU General Public License v2.0 6 votes vote down vote up
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
  """
  Returns a bytestring version of 's', encoded as specified in 'encoding'.

  If strings_only is True, don't convert (some) non-string-like objects.
  """
  if strings_only and isinstance(s, (types.NoneType, int)):
    return s
  if not isinstance(s, basestring):
    try:
      return str(s)
    except UnicodeEncodeError:
      if isinstance(s, Exception):
        # An Exception subclass containing non-ASCII data that doesn't
        # know how to print itself properly. We shouldn't raise a
        # further exception.
        return ' '.join([smart_str(arg, encoding, strings_only,
                                   errors) for arg in s])
      return unicode(s).encode(encoding, errors)
  elif isinstance(s, unicode):
    return s.encode(encoding, errors)
  elif s and encoding != 'utf-8':
    return s.decode('utf-8', errors).encode(encoding, errors)
  else:
    return s 
Example #3
Source File: ebs.py    From flocker with Apache License 2.0 6 votes vote down vote up
def __init__(self, requested, discovered):
        """
        :param FilePath requested: The requested device name.
        :param discovered: A ``FilePath`` giving the path of the device which
            was discovered on the system or ``None`` if no new device was
            discovered at all.
        """
        # It would be cool to replace this logic with pyrsistent typed fields
        # but Exception and PClass have incompatible layouts (you can't have an
        # exception that's a PClass).
        if not isinstance(requested, FilePath):
            raise TypeError(
                "requested must be FilePath, not {}".format(type(requested))
            )
        if not isinstance(discovered, (FilePath, NoneType)):
            raise TypeError(
                "discovered must be None or FilePath, not {}".format(
                    type(discovered)
                )
            )

        self.requested = requested
        self.discovered = discovered 
Example #4
Source File: recipe-68430.py    From code with MIT License 6 votes vote down vote up
def getRow(self, key):
        """Gets or creates the row subdirectory matching key.

        Note that the "rows" returned by this method need not be complete.
        They will contain only the items corresponding to the keys that
        have actually been inserted.  Other items will not be present,
        in particular they will not be represented by None."""
        
        # Get whatever is located at the first key
        thing = self.get(key, None)

        # If thing is a dictionary, return it.
        if isinstance(thing, dictionary):
            row = thing

        # If thing is None, create a new dictionary and return that.
        elif isinstance(thing, types.NoneType):
            row = {}
            self[key] = row

        # If thing is neither a dictionary nor None, then it's an error.
        else:
            row = None
            raise RaggedArrayException, "getRow: thing was not a dictionary."
        return row 
Example #5
Source File: util.py    From malwareHunter with GNU General Public License v2.0 6 votes vote down vote up
def coerce_cache_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str,), "Cache type must be a string."),
        ('enabled', (bool, types.NoneType), "enabled must be true/false "
         "if present."),
        ('expire', (int, types.NoneType), "expire must be an integer representing "
         "how many seconds the cache is valid for"),
        ('regions', (list, tuple, types.NoneType), "Regions must be a "
         "comma seperated list of valid regions"),
        ('key_length', (int, types.NoneType), "key_length must be an integer "
         "which indicates the longest a key can be before hashing"),
    ]
    return verify_rules(params, rules) 
Example #6
Source File: util.py    From malwareHunter with GNU General Public License v2.0 6 votes vote down vote up
def coerce_cache_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str,), "Cache type must be a string."),
        ('enabled', (bool, types.NoneType), "enabled must be true/false "
         "if present."),
        ('expire', (int, types.NoneType), "expire must be an integer representing "
         "how many seconds the cache is valid for"),
        ('regions', (list, tuple, types.NoneType), "Regions must be a "
         "comma seperated list of valid regions"),
        ('key_length', (int, types.NoneType), "key_length must be an integer "
         "which indicates the longest a key can be before hashing"),
    ]
    return verify_rules(params, rules) 
Example #7
Source File: conf.py    From ANALYSE with GNU Affero General Public License v3.0 6 votes vote down vote up
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_unicode, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if not isinstance(s, basestring,):
        if hasattr(s, '__unicode__'):
            s = unicode(s)
        else:
            s = unicode(str(s), encoding, errors)
    elif not isinstance(s, unicode):
        s = unicode(s, encoding, errors)
    return s 
Example #8
Source File: conf.py    From ANALYSE with GNU Affero General Public License v3.0 6 votes vote down vote up
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_unicode, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if not isinstance(s, basestring,):
        if hasattr(s, '__unicode__'):
            s = unicode(s)
        else:
            s = unicode(str(s), encoding, errors)
    elif not isinstance(s, unicode):
        s = unicode(s, encoding, errors)
    return s 
Example #9
Source File: routing.py    From PCR-GLOBWB_model with GNU General Public License v3.0 6 votes vote down vote up
def getRoutingParamAvgDischarge(self, avgDischarge, dist2celllength = None):
        # obtain routing parameters based on average (longterm) discharge
        # output: channel dimensions and 
        #         characteristicDistance (for accuTravelTime input)
        
        yMean = self.eta * pow (avgDischarge, self.nu ) # avgDischarge in m3/s
        wMean = self.tau * pow (avgDischarge, self.phi)
 
        wMean =   pcr.max(wMean,0.01) # average flow width (m) - this could be used as an estimate of channel width (assuming rectangular channels)
        wMean = pcr.cover(wMean,0.01)
        yMean =   pcr.max(yMean,0.01) # average flow depth (m) - this should NOT be used as an estimate of channel depth
        yMean = pcr.cover(yMean,0.01)
        
        # option to use constant channel width (m)
        if not isinstance(self.predefinedChannelWidth,types.NoneType):\
           wMean = pcr.cover(self.predefinedChannelWidth, wMean)
        #
        # minimum channel width (m)
        wMean = pcr.max(self.minChannelWidth, wMean)

        return (yMean, wMean) 
Example #10
Source File: jelly.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        """SecurityOptions()
        Initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "datetime": 1,
                             "time": 1,
                             "date": 1,
                             "timedelta": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        self.allowedModules = {}
        self.allowedClasses = {} 
Example #11
Source File: newjelly.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        """SecurityOptions()
        Initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        self.allowedModules = {}
        self.allowedClasses = {} 
Example #12
Source File: http_client.py    From clusterdock with Apache License 2.0 6 votes vote down vote up
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    elif not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([smart_str(arg, encoding, strings_only,
                        errors) for arg in s])
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s 
Example #13
Source File: response.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def to_string(x, quote_string=True):
    """Format value so it can be used for task log detail"""
    if isinstance(x, string_types):
        if quote_string:
            return "'%s'" % x
        else:
            return '%s' % x
    elif isinstance(x, bool):
        return str(x).lower()
    elif isinstance(x, (int, float)):
        return str(x)
    elif isinstance(x, NoneType):
        return 'null'
    elif isinstance(x, dict):
        return to_string(','.join('%s:%s' % (to_string(k, quote_string=False), to_string(v, quote_string=False))
                                  for k, v in iteritems(x)))
    elif isinstance(x, (list, tuple)):
        return to_string(','.join(to_string(i, quote_string=False) for i in x))
    return to_string(str(x)) 
Example #14
Source File: SimulationX.py    From PySimulator with GNU Lesser General Public License v3.0 6 votes vote down vote up
def getReachedSimulationTime(self):
		''' Read the current simulation time during a simulation
		'''
		sim = None
		rTime = None
		try:
			if not type(self._doc) is types.NoneType:
				sim = self._doc.Application
				sim.Interactive = False
				if self._doc.SolutionState > simReady:
					rTime = self._doc.Lookup('t').LastValue
		except:
			rTime = None
		finally:
			if not type(sim) is types.NoneType:
				sim.Interactive = True

		return rTime 
Example #15
Source File: SimulationX.py    From PySimulator with GNU Lesser General Public License v3.0 6 votes vote down vote up
def simulate(self):
		''' Run a simulation of a Modelica/SimulationX model
		'''
		sim = None
		try:
			doc = win32com.client.Dispatch(pythoncom.CoUnmarshalInterface(self._marshalled_doc, pythoncom.IID_IDispatch))
			self._marshalled_doc.Seek(0, pythoncom.STREAM_SEEK_SET)
			if not type(doc) is types.NoneType:
				sim = doc.Application
				sim.Interactive = False
				self._simulate_sync(doc)
		except win32com.client.pywintypes.com_error:
			print 'SimulationX: COM error.'
			raise(SimulatorBase.Stopping)
		except:
			print 'SimulationX: Unhandled exception.'
			import traceback
			print traceback.format_exc()
			raise(SimulatorBase.Stopping)
		finally:
			if not type(sim) is types.NoneType:
				sim.Interactive = True 
Example #16
Source File: jsonobject.py    From zstack-utility with Apache License 2.0 6 votes vote down vote up
def _dump_list(lst):
    nlst = []
    for val in lst:
        if _is_unsupported_type(val):
            raise NoneSupportedTypeError('Cannot dump val: %s, type: %s, list dump: %s' % (val, type(val), lst))
        
        if _is_primitive_types(val):
            nlst.append(val)
        elif isinstance(val, types.DictType):
            nlst.append(val)
        elif isinstance(val, types.ListType):        
            tlst = _dump_list(val)
            nlst.append(tlst)
        elif isinstance(val, types.NoneType):
            pass
        else:
            nmap = _dump(val)
            nlst.append(nmap)
    
    return nlst 
Example #17
Source File: jsonobject.py    From zstack-utility with Apache License 2.0 6 votes vote down vote up
def _dump(obj):
    if _is_primitive_types(obj): return simplejson.dumps(obj, ensure_ascii=True)
    
    ret = {}
    items = obj.iteritems() if isinstance(obj, types.DictionaryType) else obj.__dict__.iteritems()
    #items = inspect.getmembers(obj)
    for key, val in items:
        if key.startswith('_'): continue
        
        if _is_unsupported_type(obj):
            raise NoneSupportedTypeError('cannot dump %s, type:%s, object dict: %s' % (val, type(val), obj.__dict__))
        
        if _is_primitive_types(val):
            ret[key] = val
        elif isinstance(val, types.DictType):
            ret[key] = val
        elif isinstance(val, types.ListType):
            nlst = _dump_list(val)
            ret[key] = nlst
        elif isinstance(val, types.NoneType):
            pass
        else:
            nmap = _dump(val)
            ret[key] = nmap
    return ret 
Example #18
Source File: api.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _normalize_cost(cost):
    if not isinstance(cost, (types.NoneType, _ResourceCost)):
      raise ValueError('cost must be a None or ResourceCost , got %r' % (cost,))
    return cost or _ResourceCost.zero() 
Example #19
Source File: api.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def get_text(self, url, step_name=None, headers=None, transient_retry=True,
               timeout=None, default_test_data=None):
    """GET data at given URL and writes it to file.

    Args:
      * url: URL to request.
      * step_name: optional step name, 'fetch <url>' by default.
      * headers: a {header_name: value} dictionary for HTTP headers.
      * transient_retry (bool or int): Determines how transient HTTP errorts
          (>500) will be retried. If True (default), errors will be retried up
          to 10 times. If False, no transient retries will occur. If an integer
          is supplied, this is the number of transient retries to perform. All
          retries have exponential backoff applied.
      * timeout: Timeout (see step.__call__).
      * default_test_data (str): If provided, use this as the text output when
          testing if no overriding data is available.

    **Returns (UrlApi.Response)** - Response with the content as its output
    value.

    **Raises:**
      * HTTPError, InfraHTTPError: if the request failed.
      * ValueError: If the request was invalid.
    """
    assert isinstance(default_test_data, (types.NoneType, str))
    return self._get_step(url, None, step_name, headers, transient_retry,
                          None, False, timeout, default_test_data) 
Example #20
Source File: encoding.py    From lambda-packs with MIT License 5 votes vote down vote up
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    ) 
Example #21
Source File: test_descr.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_unsubclassable_types(self):
        with self.assertRaises(TypeError):
            class X(types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(object, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, object):
                pass
        class O(object):
            pass
        with self.assertRaises(TypeError):
            class X(O, types.NoneType):
                pass
        with self.assertRaises(TypeError):
            class X(types.NoneType, O):
                pass

        class X(object):
            pass
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType,
        with self.assertRaises(TypeError):
            X.__bases__ = object, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, object
        with self.assertRaises(TypeError):
            X.__bases__ = O, types.NoneType
        with self.assertRaises(TypeError):
            X.__bases__ = types.NoneType, O 
Example #22
Source File: resolver.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def __coerce__(self, value):
        t = type(value)
        if t == types.NoneType:
            return (True, False)
        return (value, t(self.value)) 
Example #23
Source File: bigquery_table_metadata.py    From gcp-census with Apache License 2.0 5 votes vote down vote up
def __init__(self, table):
        assert isinstance(table, (dict, NoneType))
        self.table = table 
Example #24
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def X(self, value):
        """sets the X coordinate"""
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._x = value
    #---------------------------------------------------------------------- 
Example #25
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def Y(self, value):
        """ sets the Y coordinate """
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._y = value
    #---------------------------------------------------------------------- 
Example #26
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def Z(self, value):
        """ sets the Z coordinate """
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._z = value
    #---------------------------------------------------------------------- 
Example #27
Source File: queue.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def setting_error_event_info(rid_or_record_dict):
        """
        Set error event info (rid and optionally id) on any raised Exception.

        (For better error inspection when analyzing logs...)

        Args:
            `rid_or_record_dict`:
                Either a message rid (a string) or an event data
                (a RecordDict instance or just a dict).

        To be used in subclasses in input_callback or methods called by it.
        Some simple examples:

            event_rid = <some operations...>
            with self.setting_error_event_info(event_rid):
                <some operations that may raise errors>

            event_record_dict = <some operations...>
            with self.setting_error_event_info(event_record_dict):
                <some operations that may raise errors>
        """
        if isinstance(rid_or_record_dict, (basestring, types.NoneType)):
            event_rid = rid_or_record_dict
            event_id = None
        else:
            event_rid = rid_or_record_dict.get('rid')
            event_id = rid_or_record_dict.get('id')

        try:
            yield
        except Exception as exc:
            # see also: _get_error_event_info_msg() above
            if getattr(exc, '_n6_event_rid', None) is None:
                exc._n6_event_rid = event_rid
            if getattr(exc, '_n6_event_id', None) is None:
                exc._n6_event_id = event_id
            raise 
Example #28
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def isNonPrimitiveInstance(x):
        return isinstance(x,types.InstanceType) or not isinstance(x,(float,int,long,type,tuple,list,dict,bool,unicode,str,buffer,complex,slice,types.NoneType,
                    types.FunctionType,types.LambdaType,types.CodeType,types.GeneratorType,
                    types.ClassType,types.UnboundMethodType,types.MethodType,types.BuiltinFunctionType,
                    types.BuiltinMethodType,types.ModuleType,types.FileType,types.XRangeType,
                    types.TracebackType,types.FrameType,types.EllipsisType,types.DictProxyType,
                    types.NotImplementedType,types.GetSetDescriptorType,types.MemberDescriptorType
                    )) 
Example #29
Source File: wrapper.py    From pymetabiosis with MIT License 5 votes vote down vote up
def init_cpy_to_pypy_converters():
    global cpy_to_pypy_converters

    import __builtin__
    builtin = pymetabiosis.module.import_module("__builtin__", noconvert=True)
    types = pymetabiosis.module.import_module("types")

    global cpy_operator
    cpy_operator = pymetabiosis.import_module('operator', noconvert=True)

    cpy_to_pypy_converters = {
            builtin.int._cpyobj : pypy_convert_int,
            builtin.float._cpyobj : pypy_convert_float,
            builtin.str._cpyobj : pypy_convert_string,
            builtin.unicode._cpyobj : pypy_convert_unicode,
            builtin.tuple._cpyobj : pypy_convert_tuple,
            builtin.dict._cpyobj : pypy_convert_dict,
            builtin.list._cpyobj : pypy_convert_list,
            builtin.bool._cpyobj : pypy_convert_bool,
            builtin.type._cpyobj : pypy_convert_type,
            types.NoneType._cpyobj : pypy_convert_None,
            }

    converted_types = ['int', 'float', 'bool', 'str', 'unicode']
    for _type in converted_types:
        cpy_type = getattr(builtin, _type)._cpyobj
        pypy_type = getattr(__builtin__, _type)
        cpy_to_pypy_types[cpy_type] = pypy_type
        pypy_to_cpy_types[pypy_type] = cpy_type 
Example #30
Source File: util.py    From malwareHunter with GNU General Public License v2.0 5 votes vote down vote up
def coerce_session_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str, types.NoneType), "Session type must be a string."),
        ('cookie_expires', (bool, datetime, timedelta, int), "Cookie expires was "
         "not a boolean, datetime, int, or timedelta instance."),
        ('cookie_domain', (str, types.NoneType), "Cookie domain must be a "
         "string."),
        ('cookie_path', (str, types.NoneType), "Cookie path must be a "
         "string."),
        ('id', (str,), "Session id must be a string."),
        ('key', (str,), "Session key must be a string."),
        ('secret', (str, types.NoneType), "Session secret must be a string."),
        ('validate_key', (str, types.NoneType), "Session encrypt_key must be "
         "a string."),
        ('encrypt_key', (str, types.NoneType), "Session validate_key must be "
         "a string."),
        ('secure', (bool, types.NoneType), "Session secure must be a boolean."),
        ('httponly', (bool, types.NoneType), "Session httponly must be a boolean."),
        ('timeout', (int, types.NoneType), "Session timeout must be an "
         "integer."),
        ('auto', (bool, types.NoneType), "Session is created if accessed."),
        ('webtest_varname', (str, types.NoneType), "Session varname must be "
         "a string."),
    ]
    opts = verify_rules(params, rules)
    cookie_expires = opts.get('cookie_expires')
    if cookie_expires and isinstance(cookie_expires, int) and \
       not isinstance(cookie_expires, bool):
        opts['cookie_expires'] = timedelta(seconds=cookie_expires)
    return opts