本文整理匯總了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)
示例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
示例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
示例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
示例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)
示例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
示例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)
示例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 = {}
示例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 = {}
示例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
示例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))
示例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
示例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
示例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
示例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