Search code examples
pythonfunctionvariablesreturncall

Function Call Variables Same as In Function


I am somewhat new to Python--beginner moving to intermediate--and would like to know how more experienced Python coders name their call and function variables.

Specifically, I like to name the call variables the same as the called function's 'receive' variables. Ditto the return variables.

Works fine, but are there problems I could run into, outside of changing a variable to global in the future?

An example call: v_Array = f_InitSpecified2DArray(v_Width,v_Length) The example called or 'receiving' function: def f_InitSpecified2DArray(v_Width, v_Length): And I do the same in the return as well: return v_Array

def f_InitSpecified2DArray(v_Width, v_Length):
    v_Array = [v_Width, v_Length]
    return v_Array

v_Array = f_InitSpecified2DArray(v_Width,v_Length)

The question is: Shall I expect any conflict resulting from reuse of name v_Array inside the function return and later in the calling code, where it goes assigned into variable with the same name v_Array?

Thanks.


Solution

  • No, this will not cause you difficulties, and doesn't cause confusion - for you, your readers, or the Python interpreter. Certainly it's less confusing than making up a new name just to differ from the parameter name, which is unnecessary. In fact, you'll often encounter the same name being used for both a named parameter and its argument, as in

    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    

    which comes from doctest.py in the standard library (for Python 3.3).

    It's instructive to search the standard library for this pattern, <name>=<same_name> (abuse of notation which I'll rectify in a moment), as its occurrences are examples of just what you're asking about. On OS X and Linux, the following command will show all lines in the standard library (plus site-packages) with occurrences of the pattern:

    grep -Er --include=*.py '(\b[[:alnum:]]+\b)=\1\b' /path/to/pythonlib
    

    On a Mac, for example, /path/to/pythonlib for Python 3.3 is usually /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3.

    This command shows how many lines feature the construct, many of which have multiple occurrences:

    grep -Er --include=*.py '(\b[[:alnum:]]+\b)=\1\b' /path/to/pythonlib | wc -l
    

    I get a count of 1129, which includes a few dozen in my site-packages subdirectory. In other words, it's quite common.