Python __builtin__ 模块,int() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用__builtin__.int()。
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
self.comments = comments
# Delimiter is a character
if isinstance(delimiter, unicode):
delimiter = delimiter.encode('ascii')
if (delimiter is None) or _is_bytes_like(delimiter):
delimiter = delimiter or None
_handyman = self._delimited_splitter
# Delimiter is a list of field widths
elif hasattr(delimiter, '__iter__'):
_handyman = self._variablewidth_splitter
idx = np.cumsum([0] + list(delimiter))
delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
# Delimiter is a single integer
elif int(delimiter):
(_handyman, delimiter) = (
self._fixedwidth_splitter, int(delimiter))
else:
(_handyman, delimiter) = (self._delimited_splitter, None)
self.delimiter = delimiter
if autostrip:
self._handyman = self.autostrip(_handyman)
else:
self._handyman = _handyman
#
def _strict_call(self, value):
try:
# We check if we can convert the value using the current function
new_value = self.func(value)
# In addition to having to check whether func can convert the
# value,we also have to make sure that we don't get overflow
# errors for integers.
if self.func is int:
try:
np.array(value, dtype=self.type)
except OverflowError:
raise ValueError
# We're still here so we can Now return the new value
return new_value
except ValueError:
if value.strip() in self.missing_values:
if not self._status:
self._checked = False
return self.default
raise ValueError("Cannot convert string '%s'" % value)
#
def __init__(self, None)
self.delimiter = delimiter
if autostrip:
self._handyman = self.autostrip(_handyman)
else:
self._handyman = _handyman
#
def _strict_call(self, dtype=self.type)
except OverflowError:
raise ValueError
# We're still here so we can Now return the new value
return new_value
except ValueError:
if value.strip() in self.missing_values:
if not self._status:
self._checked = False
return self.default
raise ValueError("Cannot convert string '%s'" % value)
#
def handle_elif(self, span, cond):
'''Should be called to signalize an elif directive.
Args:
span (tuple of int): Start and end line of the directive.
cond (str): String representation of the branching condition.
'''
self._check_for_open_block(span, 'elif')
block = self._open_blocks[-1]
directive, _, spans = block[0:3]
self._check_if_matches_last(directive, 'if', spans[-1], 'elif')
conds, contents = block[3:5]
conds.append(cond)
contents.append(self._curnode)
spans.append(span)
self._curnode = []
def handle_enddef(self, name):
'''Should be called to signalize an enddef directive.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the enddef statement. Could be None,if enddef
was specified without name.
'''
self._check_for_open_block(span, 'enddef')
block = self._open_blocks.pop(-1)
directive, fname, 'def', 'enddef')
defname, argexpr, dummy = block[3:6]
if name is not None and name != defname:
msg = "wrong name in enddef directive "\
"(expected '{0}',got '{1}')".format(defname, name)
raise FyppFatalError(msg, span)
spans.append(span)
block = (directive, spans, defname, self._curnode)
self._curnode = self._path.pop(-1)
self._curnode.append(block)
def handle_nextarg(self, name):
'''Should be called to signalize a nextarg directive.
Args:
span (tuple of int): Start and end line of the directive.
name (str or None): Name of the argument following next or
None if it should be the next positional argument.
'''
self._check_for_open_block(span, 'nextarg')
block = self._open_blocks[-1]
directive, spans = block[0:3]
self._check_if_matches_last(
directive, 'call', 'nextarg')
args, argnames = block[5:7]
args.append(self._curnode)
spans.append(span)
if name is not None:
argnames.append(name)
elif argnames:
msg = 'non-keyword argument following keyword argument'
raise FyppFatalError(msg, span)
self._curnode = []
def _set_array_types():
ibytes = [1, 2, 4, 8, 16, 32, 64]
fbytes = [2, 10, 12, 64]
for bytes in ibytes:
bits = 8*bytes
_add_array_type('int', bits)
_add_array_type('uint', bits)
for bytes in fbytes:
bits = 8*bytes
_add_array_type('float', bits)
_add_array_type('complex', 2*bits)
_gi = dtype('p')
if _gi.type not in sctypes['int']:
indx = 0
sz = _gi.itemsize
_lst = sctypes['int']
while (indx < len(_lst) and sz >= _lst[indx](0).itemsize):
indx += 1
sctypes['int'].insert(indx, _gi.type)
sctypes['uint'].insert(indx, dtype('P').type)
def __init__(self, None)
self.delimiter = delimiter
if autostrip:
self._handyman = self.autostrip(_handyman)
else:
self._handyman = _handyman
#
def _strict_call(self, dtype=self.type)
except OverflowError:
raise ValueError
# We're still here so we can Now return the new value
return new_value
except ValueError:
if value.strip() in self.missing_values:
if not self._status:
self._checked = False
return self.default
raise ValueError("Cannot convert string '%s'" % value)
#
def __init__(self, None)
self.delimiter = delimiter
if autostrip:
self._handyman = self.autostrip(_handyman)
else:
self._handyman = _handyman
#
def _strict_call(self, dtype=self.type)
except OverflowError:
raise ValueError
# We're still here so we can Now return the new value
return new_value
except ValueError:
if value.strip() in self.missing_values:
if not self._status:
self._checked = False
return self.default
raise ValueError("Cannot convert string '%s'" % value)
#
def __init__(self, None)
self.delimiter = delimiter
if autostrip:
self._handyman = self.autostrip(_handyman)
else:
self._handyman = _handyman
#
def _strict_call(self, dtype=self.type)
except OverflowError:
raise ValueError
# We're still here so we can Now return the new value
return new_value
except ValueError:
if value.strip() in self.missing_values:
if not self._status:
self._checked = False
return self.default
raise ValueError("Cannot convert string '%s'" % value)
#
def __init__(self, None)
self.delimiter = delimiter
if autostrip:
self._handyman = self.autostrip(_handyman)
else:
self._handyman = _handyman
#
def _strict_call(self, dtype=self.type)
except OverflowError:
raise ValueError
# We're still here so we can Now return the new value
return new_value
except ValueError:
if value.strip() in self.missing_values:
if not self._status:
self._checked = False
return self.default
raise ValueError("Cannot convert string '%s'" % value)
#
def _evalname(name):
k = 0
for ch in name:
if ch in '0123456789':
break
k += 1
try:
bits = int(name[k:])
except ValueError:
bits = 0
base = name[:k]
return base, bits
def _add_aliases():
for a in typeinfo.keys():
name = english_lower(a)
if not isinstance(typeinfo[a], tuple):
continue
typeobj = typeinfo[a][-1]
# insert bit-width version for this class (if relevant)
base, bit, char = bitname(typeobj)
if base[-3:] == 'int' or char[0] in 'ui':
continue
if base != '':
myname = "%s%d" % (base, bit)
if ((name != 'longdouble' and name != 'clongdouble') or
myname not in allTypes.keys()):
allTypes[myname] = typeobj
sctypeDict[myname] = typeobj
if base == 'complex':
na_name = '%s%d' % (english_capitalize(base), bit//2)
elif base == 'bool':
na_name = english_capitalize(base)
sctypeDict[na_name] = typeobj
else:
na_name = "%s%d" % (english_capitalize(base), bit)
sctypeDict[na_name] = typeobj
sctypeNA[na_name] = typeobj
sctypeDict[na_name] = typeobj
sctypeNA[typeobj] = na_name
sctypeNA[typeinfo[a][0]] = na_name
if char != '':
sctypeDict[char] = typeobj
sctypeNA[char] = na_name
def _add_integer_aliases():
_ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE']
for ctype in _ctypes:
val = typeinfo[ctype]
bits = val[2]
charname = 'i%d' % (bits//8,)
ucharname = 'u%d' % (bits//8,)
intname = 'int%d' % bits
UIntname = 'UInt%d' % bits
Intname = 'Int%d' % bits
uval = typeinfo['U'+ctype]
typeobj = val[-1]
utypeobj = uval[-1]
if intname not in allTypes.keys():
uintname = 'uint%d' % bits
allTypes[intname] = typeobj
allTypes[uintname] = utypeobj
sctypeDict[intname] = typeobj
sctypeDict[uintname] = utypeobj
sctypeDict[Intname] = typeobj
sctypeDict[UIntname] = utypeobj
sctypeDict[charname] = typeobj
sctypeDict[ucharname] = utypeobj
sctypeNA[Intname] = typeobj
sctypeNA[UIntname] = utypeobj
sctypeNA[charname] = typeobj
sctypeNA[ucharname] = utypeobj
sctypeNA[typeobj] = Intname
sctypeNA[utypeobj] = UIntname
sctypeNA[val[0]] = Intname
sctypeNA[uval[0]] = UIntname
def issubclass_(arg1, arg2):
"""
Determine if a class is a subclass of a second class.
`issubclass_` is equivalent to the Python built-in ``issubclass``,
except that it returns False instead of raising a TypeError if one
of the arguments is not a class.
Parameters
----------
arg1 : class
Input class. True is returned if `arg1` is a subclass of `arg2`.
arg2 : class or tuple of classes.
Input class. If a tuple of classes,True is returned if `arg1` is a
subclass of any of the tuple elements.
Returns
-------
out : bool
Whether `arg1` is a subclass of `arg2` or not.
See Also
--------
issubsctype,issubdtype,issctype
Examples
--------
>>> np.issubclass_(np.int32,np.int)
True
>>> np.issubclass_(np.int32,np.float)
False
"""
try:
return issubclass(arg1, arg2)
except TypeError:
return False
def issubsctype(arg1, arg2):
"""
Determine if the first argument is a subclass of the second argument.
Parameters
----------
arg1,arg2 : dtype or dtype specifier
Data-types.
Returns
-------
out : bool
The result.
See Also
--------
issctype,obj2sctype
Examples
--------
>>> np.issubsctype('S8',str)
True
>>> np.issubsctype(np.array([1]),np.int)
True
>>> np.issubsctype(np.array([1]),np.float)
False
"""
return issubclass(obj2sctype(arg1), obj2sctype(arg2))
def flatten_dtype(ndtype, flatten_base=False):
"""
Unpack a structured data-type by collapsing nested fields and/or fields
with a shape.
Note that the field names are lost.
Parameters
----------
ndtype : dtype
The datatype to collapse
flatten_base : {False,True},optional
Whether to transform a field with a shape into several fields or not.
Examples
--------
>>> dt = np.dtype([('name','S4'),('x',float),('y',
... ('block',int,(2,3))])
>>> np.lib._iotools.flatten_dtype(dt)
[dtype('|S4'),dtype('float64'),dtype('int32')]
>>> np.lib._iotools.flatten_dtype(dt,flatten_base=True)
[dtype('|S4'),dtype('int32'),
dtype('int32'),
dtype('int32')]
"""
names = ndtype.names
if names is None:
if flatten_base:
return [ndtype.base] * int(np.prod(ndtype.shape))
return [ndtype.base]
else:
types = []
for field in names:
info = ndtype.fields[field]
flat_dt = flatten_dtype(info[0], flatten_base)
types.extend(flat_dt)
return types
def _evalname(name):
k = 0
for ch in name:
if ch in '0123456789':
break
k += 1
try:
bits = int(name[k:])
except ValueError:
bits = 0
base = name[:k]
return base, bits
def _add_aliases():
for a in typeinfo.keys():
name = english_lower(a)
if not isinstance(typeinfo[a], bit)
sctypeDict[na_name] = typeobj
sctypeNA[na_name] = typeobj
sctypeDict[na_name] = typeobj
sctypeNA[typeobj] = na_name
sctypeNA[typeinfo[a][0]] = na_name
if char != '':
sctypeDict[char] = typeobj
sctypeNA[char] = na_name
def _add_integer_aliases():
_ctypes = ['LONG',)
intname = 'int%d' % bits
UIntname = 'UInt%d' % bits
Intname = 'Int%d' % bits
uval = typeinfo['U'+ctype]
typeobj = val[-1]
utypeobj = uval[-1]
if intname not in allTypes.keys():
uintname = 'uint%d' % bits
allTypes[intname] = typeobj
allTypes[uintname] = utypeobj
sctypeDict[intname] = typeobj
sctypeDict[uintname] = utypeobj
sctypeDict[Intname] = typeobj
sctypeDict[UIntname] = utypeobj
sctypeDict[charname] = typeobj
sctypeDict[ucharname] = utypeobj
sctypeNA[Intname] = typeobj
sctypeNA[UIntname] = utypeobj
sctypeNA[charname] = typeobj
sctypeNA[ucharname] = utypeobj
sctypeNA[typeobj] = Intname
sctypeNA[utypeobj] = UIntname
sctypeNA[val[0]] = Intname
sctypeNA[uval[0]] = UIntname
def issubclass_(arg1, arg2)
except TypeError:
return False
def flatten_dtype(ndtype, flatten_base)
types.extend(flat_dt)
return types
def handle_include(self, fname):
'''Called when parser starts to process a new file.
It is a dummy methond and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file.
'''
self._log_event('include', filename=fname)
def handle_endinclude(self, fname):
'''Called when parser finished processing a file.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file.
'''
self._log_event('endinclude', filename=fname)
def handle_set(self, name, expr):
'''Called when parser encounters a set directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the variable.
expr (str): String representation of the expression to be assigned
to the variable.
'''
self._log_event('set', name=name, expression=expr)
def handle_def(self, args):
'''Called when parser encounters a def directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the macro to be defined.
argexpr (str): String with argument deFinition (or None)
'''
self._log_event('def', arguments=args)
def handle_enddef(self, name):
'''Called when parser encounters an enddef directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name found after the enddef directive.
'''
self._log_event('enddef', name=name)
def handle_if(self, cond):
'''Called when parser encounters an if directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
cond (str): String representation of the branching condition.
'''
self._log_event('if', condition=cond)
def handle_elif(self, cond):
'''Called when parser encounters an elif directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
cond (str): String representation of the branching condition.
'''
self._log_event('elif', condition=cond)
def handle_else(self, span):
'''Called when parser encounters an else directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('else', span)
def handle_endif(self, span):
'''Called when parser encounters an endif directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('endif', span)
def handle_for(self, varexpr, iterator):
'''Called when parser encounters a for directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
varexpr (str): String representation of the loop variable
expression.
iterator (str): String representation of the iterable.
'''
self._log_event('for', variable=varexpr, iterable=iterator)
def handle_call(self, argexpr):
'''Called when parser encounters a call directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the callable to call
argexpr (str or None): Argument expression containing additional
arguments for the call.
'''
self._log_event('call', argexpr=argexpr)
def handle_nextarg(self, name):
'''Called when parser encounters a nextarg directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str or None): Name of the argument following next or
None if it should be the next positional argument.
'''
self._log_event('nextarg', name=name)
def handle_endcall(self, name):
'''Called when parser encounters an endcall directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name found after the endcall directive.
'''
self._log_event('endcall', name=name)
def handle_eval(self, expr):
'''Called when parser encounters an eval directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
expr (str): String representation of the Python expression to
be evaluated.
'''
self._log_event('eval', expression=expr)
def handle_global(self, name):
'''Called when parser encounters a global directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the variable which should be made global.
'''
self._log_event('global', name=name)
def handle_comment(self, span):
'''Called when parser finds a preprocessor comment.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('comment', span)
def handle_mute(self, span):
'''Called when parser finds a mute directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('mute', span)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。