Python builtins.isinstance() Examples
The following are 30
code examples of builtins.isinstance().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
builtins
, or try the search function
.
Example #1
Source File: transTmpl.py From hwt with MIT License | 6 votes |
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)
Example #2
Source File: fypp.py From fypp with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #3
Source File: fypp.py From fypp with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #4
Source File: transTmpl.py From hwt with MIT License | 6 votes |
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
Example #5
Source File: transTmpl.py From hwt with MIT License | 6 votes |
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
Example #6
Source File: bitValFunctions.py From hwt with MIT License | 5 votes |
def bitsArithOp(self, other, op): other = toHVal(other, self._dtype) if not isinstance(other._dtype, Bits): raise TypeError(other._dtype) if areValues(self, other): return bitsArithOp__val(self, other, op._evalFn) else: if self._dtype.signed is None: self = self._unsigned() resT = self._dtype if isinstance(other._dtype, Bits): t0 = self._dtype t1 = other._dtype if t0.bit_length() != t1.bit_length(): if not t1.strict_width: # resize to type of this other = other._auto_cast(t1) t1 = other._dtype pass elif not t0.strict_width: # resize self to type of result self = self._auto_cast(t0) t0 = self._dtype pass else: raise TypeError("%r %r %r" % (self, op, other)) if t1.signed != resT.signed: other = other._convSign(t0.signed) else: raise TypeError("%r %r %r" % (self, op, other)) o = Operator.withRes(op, [self, other], self._dtype) return o._auto_cast(resT)
Example #7
Source File: misc.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
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
Example #8
Source File: keycloak_admin.py From python-keycloak with MIT License | 5 votes |
def assign_group_realm_roles(self, group_id, roles): """ Assign realm roles to a group :param group_id: id of groupp :param roles: roles list or role (use GroupRoleRepresentation) :return Keycloak server response """ payload = roles if isinstance(roles, list) else [roles] params_path = {"realm-name": self.realm_name, "id": group_id} data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path), data=json.dumps(payload)) return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
Example #9
Source File: keycloak_admin.py From python-keycloak with MIT License | 5 votes |
def delete_group_realm_roles(self, group_id, roles): """ Delete realm roles of a group :param group_id: id of group :param roles: roles list or role (use GroupRoleRepresentation) :return Keycloak server response """ payload = roles if isinstance(roles, list) else [roles] params_path = {"realm-name": self.realm_name, "id": group_id} data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path), data=json.dumps(payload)) return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
Example #10
Source File: transTmpl.py From hwt with MIT License | 5 votes |
def getItemWidth(self) -> int: """ Only for transactions derived from HArray :return: width of item in original array """ if not isinstance(self.dtype, HArray): raise TypeError() return (self.bitAddrEnd - self.bitAddr) // self.itemCnt
Example #11
Source File: transTmpl.py From hwt with MIT License | 5 votes |
def __repr__(self, offset: int=0): offsetStr = "".join([" " for _ in range(offset)]) try: name = self.origin[-1].name except (AttributeError, IndexError): name = None if name: name = " name:%s," % name else: name = "" s = "%s<TransTmpl%s start:%d, end:%d" % (offsetStr, name, self.bitAddr, self.bitAddrEnd) if isinstance(self.dtype, (HArray, HStream)): s += ", itemCnt:%d" % (self.itemCnt) + "\n" s += self.children.__repr__(offset=offset + 1) + "\n" s += offsetStr + ">" return s elif not self.children: return s + ">" buff = [s, ] for isLast, child in iter_with_last(self.children): buff.append(child.__repr__(offset=offset + 1)) if self.childrenAreChoice and not isLast: buff.append(offsetStr + " <OR>") buff.append(offsetStr + ">") return "\n".join(buff)
Example #12
Source File: keycloak_admin.py From python-keycloak with MIT License | 5 votes |
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)
Example #13
Source File: fypp.py From fypp with BSD 2-Clause "Simplified" License | 5 votes |
def parsefile(self, fobj): '''Parses file or a file like object. Args: fobj (str or file): Name of a file or a file like object. ''' if isinstance(fobj, str): if fobj == STDIN: self._includefile(None, sys.stdin, STDIN, os.getcwd()) else: inpfp = _open_input_file(fobj, self._encoding) self._includefile(None, inpfp, fobj, os.path.dirname(fobj)) inpfp.close() else: self._includefile(None, fobj, FILEOBJ, os.getcwd())
Example #14
Source File: fypp.py From fypp with BSD 2-Clause "Simplified" License | 5 votes |
def _func_import(self, name, *_, **__): module = self._scope.get(name, None) if module is not None and isinstance(module, types.ModuleType): return module msg = "Import of module '{0}' via '__import__' not allowed".format(name) raise ImportError(msg)
Example #15
Source File: misc.py From gimp-plugin-export-layers with GNU General Public License v3.0 | 5 votes |
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
Example #16
Source File: misc.py From arissploit with GNU General Public License v3.0 | 5 votes |
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
Example #17
Source File: misc.py From Tautulli with GNU General Public License v3.0 | 5 votes |
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
Example #18
Source File: misc.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
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
Example #19
Source File: keycloak_admin.py From python-keycloak with MIT License | 5 votes |
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
Example #20
Source File: misc.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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
Example #21
Source File: misc.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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
Example #22
Source File: utils.py From Watson with MIT License | 5 votes |
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)
Example #23
Source File: utils.py From Watson with MIT License | 5 votes |
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)
Example #24
Source File: utils.py From Watson with MIT License | 5 votes |
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))
Example #25
Source File: misc.py From deepWordBug with Apache License 2.0 | 5 votes |
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
Example #26
Source File: misc.py From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 | 5 votes |
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
Example #27
Source File: misc.py From telegram-robot-rss with Mozilla Public License 2.0 | 5 votes |
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
Example #28
Source File: misc.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
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
Example #29
Source File: misc.py From addon with GNU General Public License v3.0 | 5 votes |
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
Example #30
Source File: core.py From pythonflow with Apache License 2.0 | 5 votes |
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")