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.
...hasattr(time, 'clock_gettime') and hasattr(time, 'CLOCK_PROF')): process_time.clock_id = time.CLOCK_PROF elif (hasattr(time, 'clock_gettime') and hasattr(time, 'CLOCK_PROCESS_CPUTIME_ID')): process_time.clock_id = time.CLOCK_PROCESS_CPUTIME_ID else: process_time.clock_id = None process_time.use_getrusage = has_resource process_time.use_times = hasattr(_time, 'times') if process_time.use_times: # sysconf("SC_CLK_TCK"), or the H...
...hasattr(_manylinux, "manylinux_compatible"): result = _manylinux.manylinux_compatible( tag_major, tag_minor, tag_arch, ) if result is not None: return bool(result) else: if (tag_major, tag_minor) == (2, 5): if hasattr(_manylinux, "manylinux1_compatible"): return bool(_manylinux.manylinux1_compatible) if (tag_major, tag_minor) == (2, 12): if hasat...
...hasattr(os, 'getrandom'): return os.urandom(size) result = bytearray() try: # need a loop because getrandom() can return less bytes than # requested for different reasons while size: data = os.getrandom(size, os.GRND_NONBLOCK) result += data size -= len(data) except BlockingIOError: # OS urandom is not initialized yet: # fallback on the Python random module data = bytes(random.randrange(256) ...
...hasattr(x, 'keys'): raise ValueError("mappings do not support reverse iteration") i = len(x) while i > 0: i -= 1 yield x[i] No language syntax changes are needed. The proposal is fully backwards compatible. A C implementation and unit tests are at: https://bugs.python.org/issue834422 BDFL Pronouncement This PEP has been conditionally accepted for Py2.4. The condition means that if the function is found to be useless, it can be removed before Py2.4b1. Al...
...hasattr(self.module, 'heapify')) class PyExampleTest(ExampleTest, unittest.TestCase): module = py_heapq @unittest.skipUnless(c_heapq, 'requires the C _heapq module') class CExampleTest(ExampleTest, unittest.TestCase): module = c_heapq if __name__ == '__main__': unittest.main() The test module defines a base class (ExampleTest) with test methods that access the heapq module through a self.heapq class attribute, and two subclasses that set this attribute to either the Python or ...
...hasattr(a, '__boolean_and__') or \ hasattr(b, '__boolean_and__'): try: return a.__boolean_and__(b) except: return b.__boolean_and__(a) else: # standard behavior if a: return b else: return 0 where the __boolean_and__ special method is implemented for C-level types by another value of the third argument to the richcmp function. This method would perform a boolean comparison of the arrays (currently impleme...
...hasattr(x, "__len__") @classmethod def __subclasscheck__(cls, C): return hasattr(C, "__bases__") and hasattr(C, "__len__") This has the advantage of not requiring explicit registration. However, the semantics are hard to get exactly right given the confusing semantics of instance attributes vs. class attributes, and that a class is an instance of its metaclass; the check for __bases__ is only an approximation of the desired semantics. Strawman: Let's do it, but let's arrange it...
...hasattr(open, 'newlines'): print 'We have universal newline support' Note that this test uses the open() function rather than the file type so that it won't fail for versions of Python where the file type was not available (the file type was added to the built-in namespace in the same release as the universal newline feature was added). Additionally, note that this test fails again on Python versions >= 2.5, when open() was made a function again and is not synonymous with the file type an...
...hasattr(iterator, 'close'): iterator.close() Open Issues Definitive semantics ought to be chosen. Currently Guido favors Exception Semantics. If the generator yields a value instead of terminating, or propagating back the special exception, a special exception should be raised again on the generator side. It is still unclear whether spuriously converted special exceptions (as discussed in Possible Semantics) are a problem and what to do about them. Implementation issues should be explor...
...hasattr(type(_lhs_result), "__else__"): _expr_result = _lhs_result else (_expr RIGHT_OP RIGHT_BOUND) else: _expr_result = _lhs_result and (_expr RIGHT_OP RIGHT_BOUND) This allows types like NumPy arrays to control the behaviour of chained comparisons by returning suitably defined circuit breakers from comparison operations. The expansion of this logic to an arbitrary number of chained comparison operations would be the same as the existing expansion for and. Rationale In ultimately re...
...hasattr(spam.eggs, "ham"): print spam.eggs.ham elif hasattr(spam.eggs, "bacon"): print spam.eggs.bacon else: print "what? no meat?" You can't raise an AttributeError when the tracking information is recalculated. If it does not raise AttributeError and instead lets the tracking stand, it may be setting the programmer up for a very subtle error. One solution to this problem would be to track the shortest possible root of each dotted expression the function refers to directly. In th...
...hasattr(self, name) This was considered a cleaner and more elegant solution to the original problem. (Another suggestion was a mixin class providing dictionary-style access to an object's attributes.) The decision was made that the present PEP did not meet the burden of proof for the introduction of new syntax, a view which had been put forward by some from the beginning of the discussion. The wrapper class idea was left open as a possibility for a future PEP. References [1]Sourceforge p...
...hasattr(a, 'unittest'): testframework.execute(a.unittest) class C: def a(self): 'just a docstring' a.publish = 1 c = C() if c.a.publish: publish(c.a()) Other Uses Paul Prescod enumerated a bunch of other uses on the python-dev thread. Future Directions Here are a number of future directions to consider. Any adoption of these ideas would require a new PEP, which referenced this one, and would have to be targeted at a Python version subsequent to the 2.1 release...
...hasattr(sys, 'implementation'): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0" Backwards Compatibility Most of this PEP is already widely deployed and thus offers no compatibility concerns. There are however a few points where the PEP differs from the deployed base. Firstly, PEP 440 direct references haven't actually been deployed in the wild, but they were designed to be compatibly added, and there are no known obstacles t...
...hasattr(var, "__enter__"): var.__enter__() try: suite finally: var.__exit__() (The presence of an __exit__ method is not checked like that of __enter__ to ensure that using inappropriate objects in with: statements gives an error). If the variable is omitted, an unnamed object is allocated on the stack. In that case, the suite has no access to the unnamed object. Possible Extensions A number of potential extensions to the basic syntax have been discussed on the Python Developer...
...hasattr(path_type, '__fspath__'): raise else: if isinstance(path, (str, bytes)): return path else: raise TypeError("expected __fspath__() to return str or bytes, " "not " + type(path).__name__) raise TypeError("expected str, bytes or os.PathLike object, not " + path_type.__name__) The os.fsencode() [6] and os.fsdecode() [7] functions will be updated to accept path objects. As both functi...
...hasattr for object attributes: class Packet: data: Union[str, Missing] def send_data(packet: Packet) -> None: if hasattr(packet, 'data'): reveal_type(packet.data) # str packet_bytes = packet.data.encode('utf-8') else: reveal_type(packet.data) # Missing? error? packet_bytes = b'' socket.send(packet_bytes) or a check against locals() for local variables: def send_data(packet_data: Optional[str]) -> None: packet_bytes: Union[str, Missi...
...hasattr(backend, "build_sdist_from_vcs"): backend.build_sdist_from_vcs(...) elif hasattr(backend, "build_sdist"): backend.build_sdist(...) else: # error handling In the alternative where the public interface boundary is placed at the subprocess call, this is not possible -- either we need to spawn an extra process just to query what interfaces are supported (as was included in an earlier draft of PEP 516, an alternative to this), or else we give up on autonegotiation ...
...hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' return (sys._getframe(1) except AttributeError: None) # Lib/inspect.py:1350: return sys._getframe(1) if hasattr(sys, "_getframe") else None Perform some lengthy calculations in EAFP mode, handling division by zero as a sort of sticky NaN: value = (calculate(x) except ZeroDivisionError: float("nan")) try: value = calculate(x) except ZeroDivisionError: value = float("nan") Calculate the mean of a series of numbers, falling ba...
...hasattr(result, 'close'): result.close() Middleware: Components that Play Both Sides Note that a single object may play the role of a server with respect to some application(s), while also acting as an application with respect to some server(s). Such "middleware" components can perform such functions as: Routing a request to different application objects based on the target URL, after rewriting the environ accordingly. Allowing multiple applications or frameworks to run side by ...