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.
...isinstance(v, types.IntType) --> isinstance(v, int) isinstance(s, types.StringTypes) --> isinstance(s, basestring) Full use of this technique requires Python 2.3 or later (basestring was introduced in Python 2.3), but Python 2.2 is sufficient for most uses. Locating: grep types *.py | grep import Avoid Variable Names that Clash with the __builtins__ Module In Python 2.2, new built-in types were added for dict and file. Scripts should avoid assigning variable names that mask thos...
...isinstance(other, datetime): try: self_diff = self.tzinfo.__datetime_diff__ except AttributeError: self_diff = None try: other_diff = self.tzinfo.__datetime_diff__ except AttributeError: other_diff = None if self_diff is not None: if self_diff is not other_diff and self_diff.__func__ is not other_diff.__func__: raise ValueError("Cannot fi...
...isinstance(param.default, type_): raise ValueError("{func}: wrong type of a default value for {arg!r}". \ format(func=func.__qualname__, arg=param.name)) def check_type(sig, arg_name, arg_type, arg_value): # Internal function that encapsulates arguments type checking if not isinstance(arg_value, arg_type): raise ValueError("{func}: wrong type of {arg!r} argument, " \ "{exp!r} expected, got {got...
...isinstance(sec, int): raise TypeError if not isinstance(nsec, int): raise TypeError asec, nsec = divmod(nsec, 10 ** 9) sec += asec obj = tuple.__new__(cls, (sec, nsec)) obj.sec = sec obj.nsec = nsec return obj def __float__(self): return self.sec + self.nsec * 1e-9 def total_nanoseconds(self): return self.sec * 10 ** 9 + self.nsec def __add__(self, other): if not isinstance(othe...
...isinstance(x, C) returns true iff x is an instance of C or of a (direct or indirect) subclass of C. The first argument may hyave any type; if x is not an instance of any class, isinstance(x, C) always returns false. The second argument must be a class object. Sequence Unpacking Previous Python versions require an exact type match between the left hand and right hand side of "unpacking" assignments, e.g. (a, b, c) = x requires that x is a tuple with three items, wh...
...isinstance(hint, int): raise TypeError("Length hint must be an integer, not %r" % type(hint)) if hint < 0: raise ValueError("__length_hint__() should return >= 0") return hint Rationale Being able to pre-allocate lists based on the expected size, as estimated by __length_hint__, can be a significant optimization. CPython has been observed to run some code faster than PyPy, purely because of this optimization being prese...
...isinstance(a, type(list)) post[a]: # array size is unchanged len(a) == len(__old__.a) # array is ordered forall([a[i] >= a[i-1] for i in range(1, len(a))]) # all the old elements are still in the array forall(__old__.a, lambda e: __old__.a.count(e) == a.count(e)) """ To make evaluating conditions easier, the function implies is defined. With two arguments, this is similar to the logical implies (=>) operator. With three arguments...
...isinstance(m, PyModuleDef): def = m return PyModule_FromDefAndSpec(def, spec) module = m # fall back to single-phase initialization .... Objects/moduleobject.c: def PyModule_FromDefAndSpec(def, spec): name = spec.name create = None for slot, value in def.m_slots: if slot == Py_mod_create: create = value if create: m = create(spec, def) else: m = PyModule_New(name) if isinstance(m, types.ModuleType): ...
...isinstance(x, int). Which reminds me. The second argument of isinstance() may now be a tuple of classes or types. For example, isinstance(x, (int, long)) returns true when x is an int or a long (or an instance of a subclass of either of those types), and similarly isinstance(x, (str, unicode)) tests for a string of either variety. We didn't do this to isclass(). Introspecting instances of built-in types For instances of built-in types (and for new-style classes in general), x....
...isinstance(x, int). Which reminds me. The second argument of isinstance() may now be a tuple of classes or types. For example, isinstance(x, (int, long)) returns true when x is an int or a long (or an instance of a subclass of either of those types), and similarly isinstance(x, (str, unicode)) tests for a string of either variety. We didn't do this to issubclass(). (Yet. It was done to issubclass() in Python 2.3.) Introspecting instances of built-in types For instances of bui...
...isinstance(filename, (str, int)) assert isinstance(mode, str) assert buffering is None or isinstance(buffering, int) assert encoding is None or isinstance(encoding, str) assert newline in (None, "", "\n", "\r", "\r\n") modes = set(mode) if modes - set("arwb+t") or len(mode) > len(modes): raise ValueError("invalid mode: %r" % mode) reading = "r" in modes writing = "w" in modes binary = "b" in modes appending = "a" in modes updating = "+" in m...
...isinstance(mro, tuple) for base in mro: assert isinstance(base, type) # PEP 447 will change these lines: try: return base.__dict__[name] except KeyError: pass return None class object: def __getattribute__(self, name): assert isinstance(name, str) tp = type(self) descr = _PyType_Lookup(tp, name) f = None if descr is not None: f = descr.__get__ if f is not None and ...
...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 285) compile(), eval(), exec - fully support Unicode, and no longer issue a SyntaxError when their input doesn't end with a newline. (New in 2.3a2.) range() - as of 2.3b1 supports long arguments with a...
...isinstance(a, numbers.Integral) and isinstance(b, numbers.Integral): return a // b else: return a / b Bundling such a function with Python 3.x versions, together with a simple mechanism to invoke it for every appearance of a / b after an appropriate __past__ invocation, need not be onerous. Q4: What about performance? Won't the performance of newer Python versions suffer under the weight of legacy features? A4: This can be evaluated on a case-by-case basis. The major potenti...
...isinstance() test will limit code reuse and/or force any dog-like classes to inherit from Dog, whether or not that makes sense. Let's see if roles can help. @perform_role(Doglike) class Dog(Animal): ... @perform_role(Treelike) class Tree(Vegetable): ... @perform_role(SitThere) class Rock(Mineral): ... We use class decorators from PEP 3129 to associate a particular role or roles with a class. Client code can now verify that an incoming object performs the Doglike role, allowing it to h...
...isinstance(other, dict): return NotImplemented new = dict(self) new.update(other) return new def __ror__(self, other): if not isinstance(other, dict): return NotImplemented new = dict(other) new.update(self) return new def __ior__(self, other): dict.update(self, other) return self Major Objections Dict Union Is Not Commutative Union is commutative, but dict union will not be (d | e != e | d). Response There is precedent for non-commutati...
...isinstance(x, basestring) should be changed to use isinstance(x, str) instead. Pickling Left as an exercise for the reader. Copyright This document has been placed in the public domain. Source: https://github.com/python/peps/blob/master/pep-3137.txt
...isinstance(expr, SQLNode): return expr.__sql__() elif isinstance(expr, str): return "'%s'" % expr.replace("'", "''") else: return str(expr) def select(*targets): return SQLSelect(targets) #----------------------------------------------------------------- dishes = Table("dishes") customers = Table("customers") orders = Table("orders") query = select(customers.name, dishes.price, orders.amount).where( customers.cust_id == orders.cust_id and orders.dish_...