programing

PEP8 표준을 준수하기에는 너무 많은 인수로 함수 정의

nicescript 2021. 1. 13. 23:36
반응형

PEP8 표준을 준수하기에는 너무 많은 인수로 함수 정의


긴 인수 목록으로 함수를 정의했습니다. 정의 된 총 문자는 80 자 이상이며 PEP8을 준수하지 않습니다.

def my_function(argument_one, argument_two, argument_three, argument_four, argument_five):

가로 스크롤을 피하는 가장 좋은 방법은 무엇입니까?


PEP 8에 예가 나와 있습니다.

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):

이것이 공식적인 대답입니다. 개인적으로 나는 연속 줄에 실제 들여 쓰기 수준에 해당하지 않는 선행 공백이있는이 접근 방식을 싫어합니다. 내 접근 방식은 다음과 같습니다.

class Rectangle(Blob):

    def __init__(
        self, width, height,
        color='black', emphasis=None, highlight=0
    ):

. . . 또는 행이 80 자 이상이되도록하십시오.


유형 주석 을 사용하는 Python 코드의 경우 다음을 제안합니다.

def some_func(
    foo: str,
    bar: str = 'default_string',
    qux: Optional[str] = None,
    qui: Optional[int] = None,
) -> List[str]:
    """
    This is an example function.
    """
    print(foo)
    ...

당신이 사용하는 경우 yapf을 당신은 이러한 옵션을 사용할 수 있습니다 .style.yapf:

[style]
dedent_closing_brackets = true
split_arguments_when_comma_terminated = true

def my_function(argument_one, argument_two, argument_three, 
                argument_four, argument_five):

개인적으로도 @BrenBarn의 두 번째 스타일과 동일한 솔루션을 생각해 냈습니다. 나는 "불행한 얼굴"이 다른 사람들에게는 다소 드문 일 임에도 불구하고 함수 매개 변수의 들여 쓰기와 그 구현을 적절히 표현하는 방법을 좋아합니다.

요즘 PEP8 은 이러한 경우에 대한 예를 구체적으로 제공하므로 주류는 해당 스타일을 적용 할 것입니다.

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

저는 개인적으로 여는 괄호로 시작하여 들여 쓰기를 유지하면서 한 줄에 하나씩 매개 변수를 정렬하는 것을 좋아합니다. flake8그것도 행복해 보인다.

def guess_device_type(device_name: str,
                      username: str=app.config['KEY_TACACS_USER'],
                      password: str=app.config['KEY_TACACS_PASS'],
                      command: str='show version') -> str:
    """Get a device_type string for netmiko"""

나는이 방법이 매우 흥미 롭다는 것을 알게되었다.

def my_function(
        argument_one, argument_two, argument_three,
        argument_four, argument_five
):
    ...

이를 통해 코드 폴딩으로 함수 시그니처를 매우 쉽게 나타낼 수 있습니다. 예를 들어 아래 스 니펫을 고려하십시오.

def my_function(
        argument_one, argument_two, argument_three,
        argument_four, argument_five
):
    s1 = 1
    s2 = 2
    if s1 + s2:
        s3 = 3


def my_other_function(argument_one, argument_two, argument_three):
    s1 = 1
    s2 = 2
    if s1 + s2:
        s3 = 3

이 방법을 사용하면 전체 파일을 코드 폴딩하고 모든 기능 / 서명을 한 번에 볼 수 있습니다.

enter image description here


내가 추천 할 것

Even though it makes the function more verbose, for more than one argument, I think this is best (the example below is from Python):

def my_function(
    argument_one, 
    argument_two, 
    argument_three,
    argument_four, 
    argument_five,
):
    ...

Why?

  1. Having each argument on one line makes it very simple to use git diffs, since changing one variable will only show that change. If you have more than one argument on each line, it's gonna be more visually annoying later.
    • Notice that the trailing comma on the last argument makes it easier to add or remove an argument later, while also conforming to the PEP 8's Trailing Comma Convention, and yielding a better git diff later.
  2. One of the reasons I really dislike the "align the arguments with the opening parenthesis" paradigm is that it doesn't yield easily maintanable code.
    • Kevlin Henney explains it is a bad practice in his ITT 2016 - Seven Ineffective Coding Habits of Many Programmers lecture.
    • The major reason it is a bad practice is that if you change the name of the function (or it is too long), you're going to have to re-edit the spacing on all the arguments' lines, which is not at all scalable, though it may be (sometimes) (subjectively) prettier.
    • The other reason, closely related to the one immediately above, is about metaprogramming. If the codebase becomes too big, you will eventually find yourself needing to program changes, which will be hell if the spacing on arguments is different for each function.
  3. Most editors, once the parentheses are open and you press enter, will open a new line with a tab and shove the closing parenthesis to the bottom line untabbed. So, formatting the code this way is very quick and kind of standardized. For instance, this formatting is very common in JavaScript.
  4. Lastly, if you think having each argument is too unwieldy because your function might have a lot of arguments, I would say that you're compromising easy formatting of your code due to rare exceptions.
    • Don't legislate by exceptions.
    • If your function has a lot of arguments, you're probably doing something wrong. Break it into more (sub)functions and classes.

ReferenceURL : https://stackoverflow.com/questions/24988162/define-functions-with-too-many-arguments-to-abide-by-pep8-standard

반응형