Search code examples
pythonargumentsdefault

What is "=- 1" in a python method's argument list?


On the following page: subprocess.popen, in the argument list of popen() there is a "pipesize=- 1". Since it pops up at a few places, it does not seem to be a typo.

As for what this may be, however, so far eluded my curiosity.

What does the "=- 1" mean?


Solution

  • That is likely an error with the documentation. It should look like pipesize = -1. But, regardless, it is a default value for an argument.

    Parameters and Arguments in Functions

    By default, all parameters in a function signature MUST be passed an argument when you call the function:

    def f(x):
        pass
    
    f("argument for x")
    

    The code above will successfully run without any errors. x is a required parameter of function f, and I correctly passed a positional argument to x.

    What if I don't pass an argument to a required parameter?

    When given this code, it results in an exception called TypeError:

    def f(x):
        pass
    
    f() # TypeError: f() missing 1 required positional argument: 'x'
    

    This happens because, as stated above, x MUST be passed based on the current function signature of f.

    Specifying optional arguments

    Now, I will provide a default value for parameter x in function f:

    def f(x=None):
        pass
    
    f()
    

    This code will also successfully run, like the first implementation of function f. But, here the function signature looks different and we didn't pass anything when we called f. x=None says that "if x isn't passed an argument in the function call to f, it should be passed None as an argument".

    Default vs. Non-Default Parameters

    It is important to note that parameters with defaults MUST appear, in the function signature, after ALL required parameters:

    def f(x=None, y):
        pass
    

    This implementation of f will result in SyntaxError: non-default argument follows default argument. It makes sense that default arguments would have to be specified, in the function signature, after ALL non-default arguments. If Python didn't raise an error for the syntactically incorrect function signature of f above, we could accidentally pass an argument to x instead of y when we do not want to.