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.
...lent to omitting it. In particular, the statement raise class, None is equivalent to raise class() and not to raise class(None) Likewise, the statement raise class, value where value happens to be a tuple is equivalent to passing the tuple's items as individual arguments to the class constructor, rather than passing value as a single argument (and an empty tuple calls the constructor without arguments). This makes a difference because there's a difference betwee...
...lent to creating an anonymous generator function and calling it. For example: g = (x**2 for x in range(10)) print g.next() is equivalent to: def __gen(exp): for x in exp: yield x**2 g = __gen(iter(range(10))) print g.next() Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run: g = (tgtexp for var1 in exp1 if exp2 for var2 in exp3 if exp4) is equivalent to: def __gen(bound_exp): for var1 in bound_exp: ...
...len(list)) for such conversion, and PEP 281 proposes to simplify the same idiom by allowing it to be written as range(list). PEP 276 proposes to allow automatic conversion of integers to iterators, simplifying the most common half-open case but not addressing the complexities of other types of interval. Additional alternatives have been discussed on python-list. The solution described here is to allow a three-way comparison after a "for" keyword, both in the context of a for-loop and of a lis...
...length len(initializer)> for i, c in enumerate(initializer): new[i] = c return new The .__repr__() method returns a string that can be evaluated to generate a new bytes object containing a bytes literal: >>> bytes([10, 20, 30]) b'\n\x14\x1e' The object has a .decode() method equivalent to the .decode() method of the str object. The object has a classmethod .fromhex() that takes a string of characters from the set [0-9a-fA-F ] and returns a bytes object (similar to...
...len or print. A small improvement in the performance of existing code is expected. Motivation Currently third-party module authors face a dilemma when implementing functions in C. Either they can use one of the pre-existing built-in function or method classes or implement their own custom class in C. The first choice causes them to lose the ability to access the internals of the callable object. The second choice is an additional maintenance burden and, more importantly, has a significant nega...
...len(lines) < 2 or lines[0][:4] != "musl": return None match = re.match(r"Version (\d+)\.(\d+)", lines[1]) if match: return (int(match.group(1)), int(match.group(2))) return None There are currently two possible ways to find the musl library's location that a Python interpreter is running on, either with the system ldd command [ldd], or by parsing the PT_INTERP section's value from the executable's ELF header [elf]. Formatting the tag Distributions using the tag ...
...lengths. For example: [*_] matches a sequence of any length. (_, _, *_), matches any sequence of length two or more. ["a", *_, "z"] matches any sequence of length two or more that starts with "a" and ends with "z". Mapping Patterns Simplified syntax: mapping_pattern: '{' [items_pattern] '}' items_pattern: ','.key_value_pattern+ ','? key_value_pattern: | (literal_pattern | constant_pattern) ':' or_pattern | '**' capture_pattern Mapping pattern is a generalization of iterable unpacki...
...len(x) --> internal sq_length --> x.__len__() hash(x) --> internal tp_hash --> x.__hash__() iter(x) --> internal tp_iter --> x.__iter__() Following this pattern, the natural way to handle next is to add a next built-in function that behaves in exactly the same fashion. next(x) --> internal tp_iternext --> x.__next__() Further, it is proposed that the next built-in function accept a sentinel value as an optional second argument, following the style of the getattr and it...
...lent of obj.__index__() and raises an error if obj does not implement the special method. Implementation Plan Add the nb_index slot in object.h and modify typeobject.c to create the __index__ method Change the ISINT macro in ceval.c to ISINDEX and alter it to accommodate objects with the index slot defined. Change the _PyEval_SliceIndex function to accommodate objects with the index slot defined. Change all builtin objects (e.g. lists) that use the as_mapping slots for subscript access and ...
...len(seq))" problem more elegantly. (PEP 279) basestring - an abstract string type which is the base class for str (8-bit strings) and unicode. Primarily used to simplify tests for string-ness to isinstance(x, basestring). bool, True, False - these were introduced as ints in Python 2.2.1, but are now a separate type (a subtype of int). This means that True and False are now printed as the strings 'True' and 'False', respectively. As of 2.3b1, bool() without arguments returns False. (PEP ...
...lent to: locals(). PyFrame_GetLocals(f) is equivalent to: f.f_locals. Both functions will return a new reference. Changes to existing APIs The C-API function PyEval_GetLocals() will be deprecated. PyEval_Locals() should be used instead. The following three functions will become no-ops, and will be deprecated: PyFrame_FastToLocalsWithError() PyFrame_FastToLocals() PyFrame_LocalsToFast() The above four deprecated functions will be removed in 3.13. Behavior of f_locals for optimized function...
...len__ (len), __ne__ (!=). You can invoke any method from this list directly: >>> a = ['tic', 'tac'] >>> T.__len__(a) # same as len(a) 2 >>> T.append(a, 'toe') # same as a.append('toe') >>> a ['tic', 'tac', 'toe'] >>> This is just like it is for user-defined classes. Notice a familiar yet surprising name in the list: __init__. This is the domain of PEP 253. Backwards compatibility XXX Warnings and Errors XXX Implementation A partia...
...len__: O(1) -> O(n) value comparison operations: no longer benefit from O(1) length check shortcut __iter__: O(1) -> O(n) __reversed__: O(1) -> O(n) keys(): O(1) -> O(n) values(): O(1) -> O(n) items(): O(1) -> O(n) popitem(): O(1) -> O(n) The length check and value comparison operations have relatively limited opportunities for improvement: without allowing usage of a potentially stale cache, the only way to know how many variables are currently bound is to iterate over al...
...lent: (z := (y := (x := 0))) Single assignment targets other than a single NAME are not supported: # No equivalent a[i] = x self.rest = [] Priority around commas is different: x = 1, 2 # Sets x to (1, 2) (x := 1, 2) # Sets x to 1 Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x, y # Use (loc := (x, y)) info = name, phone, *rest # Use (info := (name, phone, *rest)) # No equivalent px, py, pz = position na...
...lent APIs: str(b, <encoding>[, <errors>]) is equivalent to b.decode(<encoding>[, <errors>]), and bytes(s, <encoding>[, <errors>]) is equivalent to s.encode(<encoding>[, <errors>]). There is one exception: we can convert from bytes (or bytearray) to str without specifying an encoding by writing str(b). This produces the same result as repr(b). This exception is necessary because of the general promise that any object can be printed, and printing i...
...lent to the following code (copied from PEP 343): mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present PARTIAL-BLOCK-1 f((yield foo)) PARTIAL-BLOCK-2 except: exc = False if not exit(mgr, *sys.exc_info()): raise finally: if exc: exit(mgr, None, None, None) This PEP proposes to modify with block handling to instea...
...len(hookname) == 0: hookname = 'pdb.set_trace' elif hookname == '0': return None modname, dot, funcname = hookname.rpartition('.') if dot == '': modname = 'builtins' try: module = importlib.import_module(modname) hook = getattr(module, funcname) except: warnings.warn( 'Ignoring unimportable $PYTHONBREAKPOINT: {}'.format( hookname), RuntimeWarning) return None return hook(*args,...
...lent to a dict but with different performance trade-offs.): class Context(collections.abc.Mapping): def __init__(self): self._data = {} self._in_use = False def __getitem__(self, key): return self._data[key] def __iter__(self): return iter(self._data) def __len__(self): return len(self._data) At any given moment, the threadstate holds a current Context (initialized to an empty Context when the threadstate is created); we can use Contex...
...len(data) def variance(data): # Use the Computational Formula for Variance. n = len(data) ss = sum(x**2 for x in data) - (sum(data)**2)/n return ss/(n-1) def standard_deviation(data): return math.sqrt(variance(data)) The above appears to be correct with a casual test: >>> data = [1, 2, 4, 5, 8] >>> variance(data) 7.5 But adding a constant to every data point should not change the variance: >>> data = [x+1e12 for x in data] >>> varianc...
...len__ def __len__(self): return len(self._data) # Implement abstract Mapping.__iter__ def __iter__(self): return iter(self._data) # The rest of the Mapping methods are implemented # by collections.abc.Mapping. contextvars.copy_context() is implemented as follows: def copy_context(): ts: PyThreadState = PyThreadState_Get() return ts.context.copy() contextvars.ContextVar interacts with PyThreadState.context directly: class ContextVar: def __in...