Notice: While JavaScript is not essential for this website, your interaction with the content will be limited. Please turn JavaScript on for the full experience.
...len(other) < len(self): self, other = other, self for item in self: if item in other: key, value = item d[key] = value return d.items() # And here is equality: def __eq__(self, other): if isinstance(other, (set, frozenset, d_keys)): if len(self) != len(other): return False for item in other: if item not in self: return False ...
...len(items), items=[]): # May fail, may succeed Moreover, even if syntactically and semantically legal, this kind of construct is highly confusing to other programmers, and should be avoided. Choice of spelling While this document specifies a single syntax name=>expression, alternate spellings are similarly plausible. Open for consideration are the following: def bisect(a, hi=>len(a)): def bisect(a, hi:=len(a)): def bisect(a, hi?=len(a)): An alternative reference implementation is under ...
...len <= len(self.buf) # g is a valid index into buf 0 <= self.g < len(self.buf) # p is also a valid index into buf 0 <= self.p < len(self.buf) # there are len items between get and put (self.p - self.g) % len(self.buf) == \ self.len % len(self.buf) """ Module invariants must be true after the module is loaded, and at the entry and exit of every public function within the module. Class invariants must be true afte...
...len(q): at = q.popleft() for next in graph[at]: if next not in dist: dist[next] = [dist[at], next] q.append(next) return dist.get(end) Note that this returns the path in a weird format, e.g., [[['A'], 'B'], 'D']. In particular, len(find_shortest_path(graph, 'A', 'D')) will give the incorrect answer (2, because the outer list is of length 2). This is because append is done as [dist[at], next] in...
...len($value) != len($VARS): FAIL $VARS = $value Example: [2] A pattern including a star pattern: case [$VARS] translates to: $kind = type($value).__match_container__ if $kind != MATCH_SEQUENCE: FAIL if len($value) < len($VARS): FAIL $VARS = $value # Note that $VARS includes a star expression. Example: [3] Mapping Patterns A pattern not including a double-star pattern: case {$KEYWORD_PATTERNS}: translates to: $sentinel = object() $kind = type($value).__match_container__ if...
...len(sequence)): # work with index i Looping over both elements and indices can be achieved either by the old idiom or by using the new zip built-in function [2]: for i in range(len(sequence)): e = sequence[i] # work with index i and element e or: for i, e in zip(range(len(sequence)), sequence): # work with index i and element e The Proposed Solutions There are three solutions that have been discussed. One adds a non-reserved keyword, the other adds two built-in functions. ...
...len(verfiles)-1,-1,-1) because the loop deletes selected elements from verfiles but needs to leave the rest of the list intact for further iteration. random.shuffle() uses for i in xrange(len(x)-1, 0, -1) because the algorithm is most easily understood as randomly selecting elements from an ever diminishing pool. In fact, the algorithm can be run in a forward direction but is less intuitive and rarely presented that way in literature. The replacement code for i in reversed(xrange(1, len(x))) ...
...len is the length view.readonly is whether or not the memory is read-only. */ /* After using the information and you don't need it anymore */ if (PyBuffer_Release(obj, &view) < 0) { /* error return */ } Ex. 4 A consumer that wants to be able to use any object's memory but is writing an algorithm that only handle contiguous memory could do the following: void *buf; Py_ssize_t len; char *format; int copy; copy = PyObject_GetContiguous(obj, &buf, &len, &f...
...length): ncb.Reset() ncb.Command = netbios.NCBRESET ncb.Lana_num = ord(adapters.lana[i]) if win32wnet.Netbios(ncb) != 0: continue ncb.Reset() ncb.Command = netbios.NCBASTAT ncb.Lana_num = ord(adapters.lana[i]) ncb.Callname = '*'.ljust(16) ncb.Buffer = status = netbios.ADAPTER_STATUS() if win32wnet.Netbios(ncb) != 0: continue status._unpack() bytes = status.adapter_address[:6] if len(bytes) != 6: continue return int.f...
...len=len optimizations were removed. Also, altering byte codes is one of the least clean ways to improve performance and enable cleaner coding. A more robust solution would likely involve compiler pragma directives or metavariables indicating what can be optimized (similar to const/volatile declarations). Motivation The library contains code such as _len=len which is intended to create fast local references instead of slower global lookups. Though necessary for performance, these constructs c...
...length_hint__ method on several types, such as various iterators. This method is then used by various other functions (such as list) to presize lists based on the estimate returned by __length_hint__. Types which are not sized, and thus should not define __len__, can then define __length_hint__, to allow estimating or computing a size (such as many iterators). Specification This PEP formally documents __length_hint__ for other interpreters and non-standard-library Python modules to implement...
...len(newconsts) newconsts.append(cls) if n_pos is None: n_pos = len(newconsts) newconsts.append(name) if s_pos is None: s_pos = len(newconsts) newconsts.append(__super__) if sv_pos is None: sv_pos = len(newvarnames) newvarnames.append('super') # This goes at the start of the function. It is: # # super = __super__(cls, self) # # If 'super' is a cell variable, we store to both the # local and cell vari...
...len() function, i.e., xrange(len(sequence)) Not as convenient as equivalent mechanisms in other languages, Annoying, a "wart", etc. And from time to time proposals are put forth for ways in which Python could provide a better mechanism for this idiom. Recent examples include PEP 204, "Range Literals", and PEP 212, "Loop Counter Iteration". Most often, such proposal include changes to Python's syntax and other "heavyweight" changes. Part of the difficulty here is that advocating new syntax impl...
...len__(self): return self.size + len(self.dict) def __cmp__(self, dlict): c = cmp(self.names, dlict.names) if c != 0: return c c = cmp(self.size, dlict.size) if c != 0: return c for i in range(len(self.names)): c = cmp(self.empty[i], dlict.empty[i]) if c != 0: return c if self.empty[i] is None: c = cmp(self.list[i], dlict.empty[i]) if c != 0: ...
...length input. C code: Py_uhash_t x; Py_ssize_t len; /* p is either 1, 2 or 4 byte type */ unsigned char *p; Py_UCS2 *p; Py_UCS4 *p; if (len == 0) return 0; x = (Py_uhash_t) _Py_HashSecret.prefix; x ^= (Py_uhash_t) *p << 7; for (i = 0; i < len; i++) x = (1000003 * x) ^ (Py_uhash_t) *p++; x ^= (Py_uhash_t) len; x ^= (Py_uhash_t) _Py_HashSecret.suffix; return x; Which roughly translates to Python: def fnv(p): if len(p) == 0: return 0 # bit mask, 2**32-1 or 2**6...
...len__ method form the type Sized. Both [1, 2, 3] and 'abc' belong to this type, since one can call len on them: len([1, 2, 3]) # OK len('abc') # also OK len(42) # not a member of Sized By a simple class definition, for example if one defines a class: class UserID(int): pass then all instances of this class also form a type. There are also more complex types. E.g., one can define the type FancyList as all lists containing only instances of int, str or their subclasses. ...
...len(myoptimizer.get_specialized(func))) print() import builtins builtins.chr = lambda obj: "mock" print("func(): %s" % func()) print("#specialized: %s" % len(myoptimizer.get_specialized(func))) Output: func(): A #specialized: 1 func(): mock #specialized: 0 The first call uses the specialized bytecode which returns the string "A". The second call removes the specialized code because the builtin chr() function was replaced, and executes the original bytecode calling chr(65). On a microbenchm...
...len(self.args) == 1: return str(self.args[0]) else: return str(self.args) def __repr__(self): return "%s(*%s)" % (self.__class__.__name__, repr(self.args)) No restriction is placed upon what may be passed in for args for backwards-compatibility reasons. In practice, though, only a single string argument should be used. This keeps the string representation of the exception to be a useful message about the exception that is human-readable; this is wh...
...len(b) bytes from the object and stores them in b, returning the number of bytes read. Like .read, fewer than len(b) bytes may be read, and 0 indicates end of file. None is returned if a non-blocking object has no bytes available. The length of b is never changed. .write(b: bytes) -> int Returns number of bytes written, which may be < len(b). .seek(pos: int, whence: int = 0) -> int .tell() -> int .truncate(n: int = None) -> int .close() -> None Additionally, it defines a fe...
...len(prefix):] else: return self[:] def removesuffix(self: str, suffix: str, /) -> str: # suffix='' should not call self[:-0]. if suffix and self.endswith(suffix): return self[:-len(suffix)] else: return self[:] When the arguments are instances of str subclasses, the methods should behave as though those arguments were first coerced to base str objects, and the return value should always be a base str. Methods with the corresponding semantics will be a...