On 9/21/17 12:29 PM, Tobiah wrote:
Are these completely equivalent?

def foo(thing):

         assert(thing > 0), "Thing must be greater than zero"


def foo(thing):

         if not (thing > 0): raise AssertionError("Thing must be greater than 
zero")


Other than the fact that the assertion can be turned off
with -O?


Let's see:

    Python 3.6.2 (default, Jul 17 2017, 07:05:09)
    [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def foo1(thing):
    ...   assert(thing > 0), "Thing must be greater than zero"
    ...
    >>> def foo2(thing):
    ...   if not (thing > 0): raise AssertionError("Thing must be greater than zero")
    ...
    >>> import dis
    >>> dis.dis(foo1)
      2           0 LOAD_FAST                0 (thing)
                  2 LOAD_CONST               1 (0)
                  4 COMPARE_OP               4 (>)
                  6 POP_JUMP_IF_TRUE        16
                  8 LOAD_GLOBAL              0 (AssertionError)
                 10 LOAD_CONST               2 ('Thing must be greater than zero')
                 12 CALL_FUNCTION            1
                 14 RAISE_VARARGS            1
            >>   16 LOAD_CONST               0 (None)
                 18 RETURN_VALUE
    >>> dis.dis(foo2)
      2           0 LOAD_FAST                0 (thing)
                  2 LOAD_CONST               1 (0)
                  4 COMPARE_OP               4 (>)
                  6 POP_JUMP_IF_TRUE        16
                  8 LOAD_GLOBAL              0 (AssertionError)
                 10 LOAD_CONST               2 ('Thing must be greater than zero')
                 12 CALL_FUNCTION            1
                 14 RAISE_VARARGS            1
            >>   16 LOAD_CONST               0 (None)
                 18 RETURN_VALUE
    >>>

Yes, they are completely equivalent, compiling to precisely the same bytecode.

--Ned.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to