Search code examples
pythonasserthelper

Python help function for assert


help function isn't available for assert? Why?

>>> help(assert)
  File "<stdin>", line 1
    help(assert)
         ^
SyntaxError: invalid syntax

Solution

  • To get help for keywords, you need to pass the string name of the keyword

    >>> help('assert')
    The "assert" statement
    **********************
    
    Assert statements are a convenient way to insert debugging assertions
    into a program:
    
       assert_stmt ::= "assert" expression ["," expression]
    
    The simple form, "assert expression", is equivalent to
    
       if __debug__:
           if not expression: raise AssertionError
    
    The extended form, "assert expression1, expression2", is equivalent to
    
       if __debug__:
           if not expression1: raise AssertionError(expression2)
    
    These equivalences assume that "__debug__" and "AssertionError" refer
    to the built-in variables with those names.  In the current
    implementation, the built-in variable "__debug__" is "True" under
    normal circumstances, "False" when optimization is requested (command
    line option "-O").  The current code generator emits no code for an
    assert statement when optimization is requested at compile time.  Note
    that it is unnecessary to include the source code for the expression
    that failed in the error message; it will be displayed as part of the
    stack trace.
    
    Assignments to "__debug__" are illegal.  The value for the built-in
    variable is determined when the interpreter starts.
    

    You can only use help on objects that are functions, classes, modules, or methods.

    >>> help(min)
    Help on built-in function min in module builtins:
    
    min(...)
        min(iterable, *[, default=obj, key=func]) -> value
        min(arg1, arg2, *args, *[, key=func]) -> value
    
        With a single iterable argument, return its smallest item. The
        default keyword-only argument specifies an object to return if
        the provided iterable is empty.
        With two or more arguments, return the smallest argument.
    

    If you try to use help on keywords you'll get a syntax error since they are neither objects nor strings

    >>> help(assert)
    SyntaxError: invalid syntax
    >>> help(while)
    SyntaxError: invalid syntax
    >>> help(if)
    SyntaxError: invalid syntax
    

    More details

    Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.