Python operator 模块,isNumberType() 实例源码
我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用operator.isNumberType()。
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
with test_support.check_py3k_warnings():
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
with test_support.check_py3k_warnings():
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
def __add__(self, other):
# Order of testing is important!
if isinstance(other, numpy.ndarray):
# If adding sparse and dense, result is dense
# rv = SparseVector(max(self.n, other.shape[0]), {})
rv = numpy.zeros(max(self.n, other.shape[0]), 'd')
for k in range(other.shape[0]):
rv[k] = other[k]
for k in self.values.keys():
rv[k] += self[k]
return rv
elif isSparseVector(other):
rv = SparseVector(max(self.n, other.n), {})
for k in self.values.keys():
rv[k] += self[k]
for k in other.values.keys():
rv[k] += other[k]
return rv
elif operator.isNumberType(other):
rv = SparseVector(self.n, {})
for k in self.values.keys():
rv[k] = self[k] + other
return rv
else:
raise TypeError("Cannot add with SparseVector")
def __iadd__(self, other):
# Order of testing is important!
if isinstance(other, numpy.ndarray):
self.n = max(self.n, other.shape[0])
for k in range(other.shape[0]):
self[k] += other[k]
return self
elif isSparseVector(other):
self.n = max(self.n, other.n)
inter = filter(self.values.has_key, other.values.keys())
other_only = filter(lambda x: not self.values.has_key,
other.values.keys())
for k in inter + other_only:
self[k] += other[k]
return self
elif operator.isNumberType(other):
for k in self.values.keys():
self[k] += other
return self
else:
raise TypeError("Cannot add to SparseVector")
def __imul__(self, other):
"""Element by element multiplication.
For dot product, see the helper function dot().
"""
if isinstance(other, numpy.ndarray):
self.n = max(self.n, other.shape[0])
for k in range(other.shape[0]):
self.values[k] *= other[k]
return self
elif isSparseVector(other):
self.n = max(self.n, other.n)
inter = filter(self.values.has_key, other.values.keys())
other_only = filter(lambda x: not self.values.has_key,
other.values.keys())
for k in inter + other_only:
self.values[k] *= other.values[k]
return self
elif operator.isNumberType(other):
for k in self.values.keys():
self.values[k] *= other
return self
else:
raise TypeError("Cannot multiply with SparseVector")
def __idiv__(self, other):
"""Element by element division."""
if isinstance(other, numpy.ndarray):
self.n = max(self.n, other.shape[0])
for k in range(other.shape[0]):
self[k] /= other[k]
return self
elif isSparseVector(other):
self.n = max(self.n, other.n)
inter = filter(self.values.has_key, other.values.keys())
other_only = filter(lambda x: not self.values.has_key,
other.values.keys())
for k in inter + other_only:
self[k] /= other.values[k]
return self
elif operator.isNumberType(other):
for k in self.values.keys():
self[k] /= other
return self
else:
raise TypeError("Cannot multiply with SparseVector")
def __div__(self, other):
"""Element by element division."""
if isinstance(other, numpy.ndarray):
rv = SparseVector(max(self.n, other.shape[0]), {})
for k in self.values.keys():
rv[k] = self[k] / other[k]
return rv
elif isSparseVector(other):
rv = SparseVector(max(self.n, other.n), {})
for k in filter(self.values.has_key, other.values.keys()):
rv[k] = self[k] / other[k]
return rv
elif operator.isNumberType(other):
rv = SparseVector(self.n, {})
for k in self.values.keys():
rv[k] = self[k] / other
return rv
else:
raise TypeError("Cannot multiply with SparseVector")
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
with test_support.check_py3k_warnings():
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
with test_support.check_py3k_warnings():
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
def Set(cls, value):
log.step_normal("Element [%s]: Set [%s]." % (cls.__name__, value))
if isNumberType(value):
value = str(value)
cls.__wait()
elements = env.threadlocal.BROWSER.find_elements(cls.by, cls.value)
if elements[cls.index].tag_name == "select" or elements[cls.index].tag_name == "ul":
cls.Select(value)
else:
elements[cls.index].clear()
action = webdriver.ActionChains(env.threadlocal.BROWSER)
action.send_keys_to_element(elements[cls.index], value) #????????
action.perform()
cls.__clearup()
def __init__(self, stream, cols=None, number_fmt='%8.4f', col_width=8,
col_sep=' ', output_block=False, **pars):
DataRecorder.__init__(self, **pars)
self._stream = stream
if not number_fmt.startswith('%'):
number_fmt = '%%s' % number_fmt
self._number_fmt = number_fmt
self._col_sep = col_sep
self._col_width = col_width
if operator.isSequenceType(cols) and \
not isinstance(cols, (str, unicode)):
cols = CaselessList(cols)
elif operator.isNumberType(cols):
cols = cols
else:
cols = None
self._columns = cols
self._output_block = output_block
def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number
except ImportError:
from operator import isNumberType
return isNumberType(obj)
else:
return isinstance(obj, Number)
def test_isNumberType(self):
self.assertRaises(TypeError, operator.isNumberType)
self.assertTrue(operator.isNumberType(8))
self.assertTrue(operator.isNumberType(8j))
self.assertTrue(operator.isNumberType(8L))
self.assertTrue(operator.isNumberType(8.3))
self.assertFalse(operator.isNumberType(dir()))
def test_isNumberType(self):
self.assertRaises(TypeError, operator.isNumberType)
self.assertTrue(operator.isNumberType(8))
self.assertTrue(operator.isNumberType(8j))
self.assertTrue(operator.isNumberType(8L))
self.assertTrue(operator.isNumberType(8.3))
self.assertFalse(operator.isNumberType(dir()))
def __setitem__(self, index, item):
if not isinstance(index, types.IntType):
raise KeyError("Index must be integer")
if index > self.n:
self.n = index
if not operator.isNumberType(item):
raise TypeError("Value must be numeric")
if float(item) != 0.0:
dict.__setitem__(self.values, index, item)
# Fetch item from sparse vector
def test_isNumberType(self):
self.assertRaises(TypeError, operator.isNumberType)
self.assertTrue(operator.isNumberType(8))
self.assertTrue(operator.isNumberType(8j))
self.assertTrue(operator.isNumberType(8L))
self.assertTrue(operator.isNumberType(8.3))
self.assertFalse(operator.isNumberType(dir()))
def test_isNumberType(self):
self.assertRaises(TypeError, operator.isNumberType)
self.assertTrue(operator.isNumberType(8))
self.assertTrue(operator.isNumberType(8j))
self.assertTrue(operator.isNumberType(8L))
self.assertTrue(operator.isNumberType(8.3))
self.assertFalse(operator.isNumberType(dir()))
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isNumberType(c)):
return c, 0.0
if (a is stub and b == "__add__" and isNumberType(c)):
return 1.0, c
except TypeError: pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isNumberType(c) and
d == "__add__" and isNumberType(e)):
return c, e
except TypeError: pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
##
# This class represents an image object. To create Image objects, use
# the appropriate factory functions. There's hardly ever any reason
# to call the Image constructor directly.
#
# @see #open
# @see #new
# @see #fromstring
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isNumberType(c)):
return c, 0.0
if (a is stub and b == "__add__" and isNumberType(c)):
return 1.0, c
except TypeError: pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isNumberType(c) and
d == "__add__" and isNumberType(e)):
return c, e
except TypeError: pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
##
# This class represents an image object. To create Image objects, use
# the appropriate factory functions. There's hardly ever any reason
# to call the Image constructor directly.
#
# @see #open
# @see #new
# @see #fromstring
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isNumberType(c)):
return c, 0.0
if (a is stub and b == "__add__" and isNumberType(c)):
return 1.0, c
except TypeError: pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isNumberType(c) and
d == "__add__" and isNumberType(e)):
return c, e
except TypeError: pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
##
# This class represents an image object. To create Image objects, use
# the appropriate factory functions. There's hardly ever any reason
# to call the Image constructor directly.
#
# @see #open
# @see #new
# @see #fromstring
def exec_(self):
"""**Internal method**. Execute macro as an iterator"""
self._macro_thread = threading.current_thread()
macro_status = self.getMacroStatus()
# make sure a 0.0 progress is sent
yield macro_status
# allow any macro to be paused at the beginning of its execution
self.pausePoint()
# Run the macro or obtain a generator
res = self.run(*self._in_pars)
# If macro returns a generator then running the macro means go through
# the generator steps, otherwise the macro has already ran
if isinstance(res, types.GeneratorType):
it = iter(res)
for i in it:
if operator.isMappingType(i):
new_range = i.get('range')
if new_range is not None:
macro_status['range'] = new_range
new_step = i.get('step')
if new_step is not None:
macro_status['step'] = new_step
elif operator.isNumberType(i):
macro_status['step'] = i
macro_status['state'] = 'step'
yield macro_status
# make sure a 'stop' progress is sent in case an exception occurs
macro_status['state'] = 'stop'
else:
self._out_pars = res
macro_status['step'] = 100.0
macro_status['state'] = 'finish'
yield macro_status
def _writeRecord(self, record):
if not self.isInitialized():
return
vals = []
for colname in self.labels:
val = record.data.get(colname)
if (not val is None) and (operator.isNumberType(val) and (type(val) in [int, float, long])):
vals.append(val)
elif (not val is None) and (operator.isNumberType(val)):
valsmca = []
for i in range(0, len(val)):
valsmca.append(val[i])
sufix = "1D"
if self.array.endswith(sufix):
valsmca = numpy.array(valsmca)
self.sps.putdatarow(
self.program, self.array, record.recordno, valsmca)
sufix = "0D"
if self.array.endswith(sufix):
vals = numpy.array(vals)
self.sps.putdatarow(self.program, self.array,
record.recordno, vals)
self.nopts += 1
env = {'nopts': self.nopts,
'peak': 111,
'peakpos': 34,
'fwhm': 12.3,
'fwhmpos': 45,
'com': 23}
self.putAllEnv(env)
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isNumberType(c)):
return c, 0.0
if (a is stub and b == "__add__" and isNumberType(c)):
return 1.0, c
except TypeError: pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isNumberType(c) and
d == "__add__" and isNumberType(e)):
return c, e
except TypeError: pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
##
# This class represents an image object. To create Image objects, use
# the appropriate factory functions. There's hardly ever any reason
# to call the Image constructor directly.
#
# @see #open
# @see #new
# @see #fromstring