本文整理汇总了Python中builtins.isinstance方法的典型用法代码示例。如果您正苦于以下问题:Python builtins.isinstance方法的具体用法?Python builtins.isinstance怎么用?Python builtins.isinstance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类builtins
的用法示例。
在下文中一共展示了builtins.isinstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def __init__(self, dtype: HdlType, bitAddr: int=0,
parent: Optional['TransTmpl']=None,
origin: Optional[HStructField]=None,
rel_field_path: Tuple[Union[str, int], ...]=tuple()):
self.parent = parent
assert isinstance(dtype, HdlType), dtype
assert parent is None or isinstance(parent, TransTmpl), parent
if origin is None:
origin = (dtype,)
else:
assert isinstance(origin, tuple), origin
self.origin = origin
self.dtype = dtype
self.children = []
self.itemCnt = None
self.rel_field_path = rel_field_path
self._loadFromHType(dtype, bitAddr)
示例2: _loadFromHStream
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def _loadFromHStream(self, dtype: HStream, bitAddr: int) -> int:
"""
Parse HStream type to this transaction template instance
:return: address of it's end
"""
self.children = TransTmpl(
dtype.element_t, 0, parent=self, origin=self.origin,
rel_field_path=(0,))
if not isinstance(dtype.len_min, int) or dtype.len_min != dtype.len_max:
raise ValueError("This template is ment only"
" for types of constant and finite size")
self.itemCnt = dtype.len_min
return bitAddr + dtype.element_t.bit_length() * self.itemCnt
示例3: _loadFromHType
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def _loadFromHType(self, dtype: HdlType, bitAddr: int) -> None:
"""
Parse any HDL type to this transaction template instance
"""
self.bitAddr = bitAddr
childrenAreChoice = False
if isinstance(dtype, Bits):
ld = self._loadFromBits
elif isinstance(dtype, HStruct):
ld = self._loadFromHStruct
elif isinstance(dtype, HArray):
ld = self._loadFromArray
elif isinstance(dtype, HStream):
ld = self._loadFromHStream
elif isinstance(dtype, HUnion):
ld = self._loadFromUnion
childrenAreChoice = True
else:
raise TypeError("expected instance of HdlType", dtype)
self.bitAddrEnd = ld(dtype, bitAddr)
self.childrenAreChoice = childrenAreChoice
示例4: _get_callable_argspec_py2
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def _get_callable_argspec_py2(func):
argspec = inspect.getargspec(func)
varpos = argspec.varargs
varkw = argspec.keywords
args = argspec.args
tuplearg = False
for elem in args:
tuplearg = tuplearg or isinstance(elem, list)
if tuplearg:
msg = 'tuple argument(s) found'
raise FyppFatalError(msg)
defaults = {}
if argspec.defaults is not None:
for ind, default in enumerate(argspec.defaults):
iarg = len(args) - len(argspec.defaults) + ind
defaults[args[iarg]] = default
return args, defaults, varpos, varkw
示例5: _formatted_exception
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def _formatted_exception(exc):
error_header_formstr = '{file}:{line}: '
error_body_formstr = 'error: {errormsg} [{errorclass}]'
if not isinstance(exc, FyppError):
return error_body_formstr.format(
errormsg=str(exc), errorclass=exc.__class__.__name__)
out = []
if exc.fname is not None:
if exc.span[1] > exc.span[0] + 1:
line = '{0}-{1}'.format(exc.span[0] + 1, exc.span[1])
else:
line = '{0}'.format(exc.span[0] + 1)
out.append(error_header_formstr.format(file=exc.fname, line=line))
out.append(error_body_formstr.format(errormsg=exc.msg,
errorclass=exc.__class__.__name__))
if exc.cause is not None:
out.append('\n' + _formatted_exception(exc.cause))
out.append('\n')
return ''.join(out)
示例6: pow
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def pow(x, y, z=_SENTINEL):
"""
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
"""
# Handle newints
if isinstance(x, newint):
x = long(x)
if isinstance(y, newint):
y = long(y)
if isinstance(z, newint):
z = long(z)
try:
if z == _SENTINEL:
return _builtin_pow(x, y)
else:
return _builtin_pow(x, y, z)
except ValueError:
if z == _SENTINEL:
return _builtin_pow(x+0j, y)
else:
return _builtin_pow(x+0j, y, z)
# ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
# callable = __builtin__.callable
示例7: style
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def style(name, element):
def _style_tags(tags):
if not tags:
return ''
return u'[{}]'.format(', '.join(
style('tag', tag) for tag in tags
))
def _style_short_id(id):
return style('id', id[:7])
formats = {
'project': {'fg': 'magenta'},
'tags': _style_tags,
'tag': {'fg': 'blue'},
'time': {'fg': 'green'},
'error': {'fg': 'red'},
'date': {'fg': 'cyan'},
'short_id': _style_short_id,
'id': {'fg': 'white'}
}
fmt = formats.get(name, {})
if isinstance(fmt, dict):
return click.style(element, **fmt)
else:
# The fmt might be a function if we need to do some computation
return fmt(element)
示例8: safe_save
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def safe_save(path, content, ext='.bak'):
"""
Save given content to file at given path safely.
`content` may either be a (unicode) string to write to the file, or a
function taking one argument, a file object opened for writing. The
function may write (unicode) strings to the file object (but doesn't need
to close it).
The file to write to is created at a temporary location first. If there is
an error creating or writing to the temp file or calling `content`, the
destination file is left untouched. Otherwise, if all is well, an existing
destination file is backed up to `path` + `ext` (defaults to '.bak') and
the temporary file moved into its place.
"""
tmpfp = tempfile.NamedTemporaryFile(mode='w+', delete=False)
try:
with tmpfp:
if isinstance(content, text_type):
tmpfp.write(content)
else:
content(tmpfp)
except Exception:
try:
os.unlink(tmpfp.name)
except (IOError, OSError):
pass
raise
else:
if os.path.exists(path):
try:
os.unlink(path + ext)
except OSError:
pass
shutil.move(path, path + ext)
shutil.move(tmpfp.name, path)
示例9: json_arrow_encoder
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def json_arrow_encoder(obj):
"""
Encodes Arrow objects for JSON output.
This function can be used with
`json.dumps(..., default=json_arrow_encoder)`, for example.
If the object is not an Arrow type, a TypeError is raised
:param obj: Object to encode
:return: JSON representation of Arrow object as defined by Arrow
"""
if isinstance(obj, arrow.Arrow):
return obj.for_json()
raise TypeError("Object {} is not JSON serializable".format(obj))
示例10: pow
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def pow(x, y, z=_SENTINEL):
"""
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
"""
# Handle newints
if isinstance(x, newint):
x = long(x)
if isinstance(y, newint):
y = long(y)
if isinstance(z, newint):
z = long(z)
try:
if z == _SENTINEL:
return _builtin_pow(x, y)
else:
return _builtin_pow(x, y, z)
except ValueError:
if z == _SENTINEL:
return _builtin_pow(x+0j, y)
else:
return _builtin_pow(x+0j, y, z)
# ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
# callable = __builtin__.callable
示例11: normalize_operation
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def normalize_operation(self, operation): # pylint:disable=W0621
"""
Normalize an operation by resolving its name if necessary.
Parameters
----------
operation : Operation or str
Operation instance or name of an operation.
Returns
-------
normalized_operation : Operation
Operation instance.
Raises
------
ValueError
If `operation` is not an `Operation` instance or an operation name.
RuntimeError
If `operation` is an `Operation` instance but does not belong to this graph.
KeyError
If `operation` is an operation name that does not match any operation of this graph.
"""
if isinstance(operation, Operation):
if operation.graph is not self:
raise RuntimeError(f"operation '{operation}' does not belong to this graph")
return operation
if isinstance(operation, str):
return self.operations[operation]
raise ValueError(f"'{operation}' is not an `Operation` instance or operation name")
示例12: evaluate_operation
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def evaluate_operation(cls, operation, context, **kwargs):
"""
Evaluate an operation or constant given a context.
"""
try:
if isinstance(operation, Operation):
return operation.evaluate(context, **kwargs)
partial = functools.partial(cls.evaluate_operation, context=context, **kwargs)
if isinstance(operation, tuple):
return tuple(partial(element) for element in operation)
if isinstance(operation, list):
return [partial(element) for element in operation]
if isinstance(operation, dict):
return {partial(key): partial(value) for key, value in operation.items()}
if isinstance(operation, slice):
return slice(*[partial(getattr(operation, attr))
for attr in ['start', 'stop', 'step']])
return operation
except Exception as ex: # pragma: no cover
stack = []
interactive = False
for frame in reversed(operation._stack): # pylint: disable=protected-access
# Do not capture any internal stack traces
if 'pythonflow' in frame.filename:
continue
# Stop tracing at the last interactive cell
if interactive and not frame.filename.startswith('<'):
break # pragma: no cover
interactive = frame.filename.startswith('<')
stack.append(frame)
stack = "".join(traceback.format_list(reversed(stack)))
message = "Failed to evaluate operation `%s` defined at:\n\n%s" % (operation, stack)
raise ex from EvaluationError(message)
示例13: auto_refresh_token
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def auto_refresh_token(self, value):
allowed_methods = {'get', 'post', 'put', 'delete'}
if not isinstance(value, Iterable):
raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
if not all(method in allowed_methods for method in value):
raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
self._auto_refresh_token = value
示例14: assign_client_role
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def assign_client_role(self, user_id, client_id, roles):
"""
Assign a client role to a user
:param user_id: id of user
:param client_id: id of client (not client-id)
:param roles: roles list or role (use RoleRepresentation)
:return Keycloak server response
"""
payload = roles if isinstance(roles, list) else [roles]
params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
data=json.dumps(payload))
return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
示例15: assign_realm_roles
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import isinstance [as 别名]
def assign_realm_roles(self, user_id, client_id, roles):
"""
Assign realm roles to a user
:param user_id: id of user
:param client_id: id of client containing role (not client-id)
:param roles: roles list or role (use RoleRepresentation)
:return Keycloak server response
"""
payload = roles if isinstance(roles, list) else [roles]
params_path = {"realm-name": self.realm_name, "id": user_id}
data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
data=json.dumps(payload))
return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)