Search code examples
pythonpydoc

pydoc.doc fail to retrieve the "os.path.sep"


I check the help utility with os.path.sep in the interactive mode and come by:

In [59]: help(os.path.sep)
Related help topics: lambda, or, and, not, in, is, BOOLEAN, COMPARISON,BITWISE, SHIFTING, BINARY, FORMATTING, POWER, UNARY, ATTRIBUTES,SUBSCRIPTS, SLICINGS, CALLS, TUPLES, LISTS, DICTIONARIES

Operator precedence


The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

However, when I try to retrieve it with pydoc

In [61]: with open("osPathSep_help.md", "w") as fout:
    ...:     pydoc.doc(os.path.sep, output=fout)
    ...:     
No Python documentation found for '/'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

In [62]: os.stat("osPathSep_help.md").st_size
Out[62]: 0

How to get the same content as the quotation?

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most


Solution

  • To understand this behaviour you have to get inside the os.path library source code. If you go inside the code then you will find all these variables

    curdir = '.'
    pardir = '..'
    extsep = '.'
    sep = '\\'
    pathsep = ';'
    altsep = '/'
    defpath = '.;C:\\bin'
    devnull = 'nul'
    

    Now what you are trying to do is access os.path.sep as a function but as you can see it is not a function but a variable with a value assigned as '\'

    So os.path.sep is always \ , thats why when you are doing help(os.path.sep) you are getting the result as

    Operator precedence

    The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

    Which will the same result as you will get when you would do

    help('\\')
    

    Now your next question would be how does it work with help?

    so if you check the source code of help it is mentioned

    """
    Define the built-in 'help'.
    This is a wrapper around pydoc.help (with a twist).
    """
    

    So help is internally using pydoc.help

    So if you are using

    pydoc.help('\\') or pydoc.help(os.path.sep) you would get your desired output.