當前位置: 首頁>>代碼示例>>Python>>正文


Python types.NoneType方法代碼示例

本文整理匯總了Python中types.NoneType方法的典型用法代碼示例。如果您正苦於以下問題:Python types.NoneType方法的具體用法?Python types.NoneType怎麽用?Python types.NoneType使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在types的用法示例。


在下文中一共展示了types.NoneType方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: breakpoint

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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) 
開發者ID:hjimce,項目名稱:Depth-Map-Prediction,代碼行數:22,代碼來源:thutil.py

示例2: smart_str

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:bitex-coin,項目名稱:backend,代碼行數:27,代碼來源:utils.py

示例3: __init__

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:ClusterHQ,項目名稱:flocker,代碼行數:25,代碼來源:ebs.py

示例4: getRow

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:ActiveState,項目名稱:code,代碼行數:27,代碼來源:recipe-68430.py

示例5: coerce_cache_params

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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) 
開發者ID:abdesslem,項目名稱:malwareHunter,代碼行數:19,代碼來源:util.py

示例6: force_unicode

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:19,代碼來源:conf.py

示例7: getRoutingParamAvgDischarge

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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) 
開發者ID:UU-Hydro,項目名稱:PCR-GLOBWB_model,代碼行數:23,代碼來源:routing.py

示例8: __init__

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 = {} 
開發者ID:kenorb-contrib,項目名稱:BitTorrent,代碼行數:24,代碼來源:jelly.py

示例9: __init__

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 = {} 
開發者ID:kenorb-contrib,項目名稱:BitTorrent,代碼行數:20,代碼來源:newjelly.py

示例10: smart_str

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:cloudera,項目名稱:clusterdock,代碼行數:27,代碼來源:http_client.py

示例11: to_string

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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)) 
開發者ID:erigones,項目名稱:esdc-ce,代碼行數:21,代碼來源:response.py

示例12: getReachedSimulationTime

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:PySimulator,項目名稱:PySimulator,代碼行數:20,代碼來源:SimulationX.py

示例13: simulate

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:PySimulator,項目名稱:PySimulator,代碼行數:24,代碼來源:SimulationX.py

示例14: _dump_list

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:zstackio,項目名稱:zstack-utility,代碼行數:22,代碼來源:jsonobject.py

示例15: _dump

# 需要導入模塊: import types [as 別名]
# 或者: from types import NoneType [as 別名]
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 
開發者ID:zstackio,項目名稱:zstack-utility,代碼行數:27,代碼來源:jsonobject.py


注:本文中的types.NoneType方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。