source

PEP8에 준거하여 E501을 방지하는 매우 긴 문자열 작성 방법

goodcode 2022. 9. 12. 11:38
반응형

PEP8에 준거하여 E501을 방지하는 매우 긴 문자열 작성 방법

PEP8은 python 프로그램의 80컬럼 룰을 밑도는 것을 권장하고 있기 때문에 긴 스트링으로 어떻게 그것을 지킬 수 있을까요?

s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."

다음 행으로 확장하려면 어떻게 해야 할까요?

s = "this is my really, really, really, really, really, really" + 
    "really long string that I'd like to shorten."

인접 문자열 상수는 자동으로 연결되므로 다음과 같이 코드화할 수 있습니다.

s = ("this is my really, really, really, really, really, really, "  
     "really long string that I'd like to shorten.")

플러스 기호 없음에 주의하고 예제 형식 뒤에 쉼표와 공백을 추가했습니다.

개인적으로 나는 백슬래시를 좋아하지 않는다.어디선가 읽었을 때 백슬래시의 용도가 실제로는 더 노골적인 이 형식을 선호하기 위해 권장되지 않는다."명백한 것이 암묵적인 것보다 낫다"는 것을 기억하라.

백슬래시는 실제로는 줄바꿈 문자를 벗어나기 때문에 명확하지 않고 유용하지 않다고 생각합니다.필요에 따라서, 그 뒤에 행 끝의 코멘트를 붙일 수 없습니다.이 작업은 연결된 문자열 상수를 사용하여 수행할 수 있습니다.

s = ("this is my really, really, really, really, really, really, " # comments ok
     "really long string that I'd like to shorten.")

첫 번째 결과로서 PEP8 링크를 반환하는 "python line length"의 구글 검색을 사용했지만, "왜 Python PEP-8이 최대 line length of 79 characters?"라는 주제에 대한 또 다른 좋은 StackOverflow 게시물에 링크합니다.

또 다른 좋은 검색어는 "피톤 회선 연속"입니다.

암묵적인 연결이 가장 깨끗한 솔루션일 수 있습니다.

s = "this is my really, really, really, really, really, really," \
    " really long string that I'd like to shorten."

Edit On Reflects On Line Continuation보다는 괄호를 사용하자는 Todd의 제안이 그가 제시하는 모든 이유로 더 낫다는 데 동의합니다.내가 유일하게 망설이는 것은 괄호로 묶인 문자열과 튜플을 비교적 쉽게 혼동할 수 있다는 것이다.

당신의 질문에서 가장 중요한 단어는 "제안"이었던 것 같습니다.

코드 기준은 웃긴 거야대부분의 경우, 이 가이던스가 작성되었을 때는 매우 좋은 근거가 됩니다(예를 들어 대부분의 단말기는 한 줄에 80자 이상의 문자를 표시할 수 없습니다).그러나 시간이 지남에 따라 기능적으로는 구식이 되어 버립니다만, 여전히 엄격하게 준수하고 있습니다.여기서 당신이 해야 할 일은 당신의 코드의 가독성과 유지보수가능성에 대해 그 특정 제안을 "깨는" 상대적인 장점을 따져보는 것입니다.

죄송합니다. 이 질문에는 답변이 없습니다.

줄 줄 바꿈 문자가 할 수 .\.

s = "this is my really, really, really, really, really, really" +  \
    " really long string that I'd like to shorten."

또는 다음과 같은 경우도 있습니다.

s = "this is my really, really, really, really, really, really"  \
    " really long string that I'd like to shorten."

패렌스도 줄을 이어가는 대신 작동하지만, 다른 사람이 태플을 가지려다가 콤마를 잊어버렸다고 생각할 위험이 있습니다.예를 들어 다음과 같습니다.

s = ("this is my really, really, really, really, really, really"
    " really long string that I'd like to shorten.")

비교:

s = ("this is my really, really, really, really, really, really",
    " really long string that I'd like to shorten.")

Python의 다이내믹 타이핑에서는 어느 쪽이든 코드가 실행될 수 있지만 의도하지 않은 코드에서는 잘못된 결과를 얻을 수 있습니다.

긴 문자열 리터럴을 삽입하여 플레이크8을 종료할 필요가 있는 경우는, 그 셧다운 디렉티브를 사용할 수 있습니다.예를 들어 테스트 루틴에서 가짜 CSV 입력을 정의했습니다.행이 있는 행으로 나누면 상당히 혼란스럽다는 것을 깨달았습니다.그래서 다음 행을 추가하기로 했습니다.# noqa: E501음음음같 뭇매하다

csv_test_content = """"STATION","DATE","SOURCE","LATITUDE","LONGITUDE","ELEVATION","NAME","REPORT_TYPE","CALL_SIGN","QUALITY_CONTROL","WND","CIG","VIS","TMP","DEW","SLP","AA1","AA2","AY1","AY2","GF1","MW1","REM"
"94733099999","2019-01-03T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","050,1,N,0010,1","22000,1,9,N","025000,1,9,9","+0260,1","+0210,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1","01,99,1,99,9,99,9,99999,9,99,9,99,9","01,1","SYN05294733 11/75 10502 10260 20210 60004 70100 333 70000="
"94733099999","2019-01-04T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","090,1,N,0021,1","22000,1,9,N","025000,1,9,9","+0378,1","+0172,1","99999,9","06,0000,9,1",,"0,1,02,1","0,1,02,1","03,99,1,99,9,99,9,99999,9,99,9,99,9","03,1","SYN04294733 11/75 30904 10378 20172 60001 70300="
"94733099999","2019-01-04T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","290,1,N,0057,1","99999,9,9,N","020000,1,9,9","+0339,1","+0201,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1",,"02,1","SYN05294733 11970 02911 10339 20201 60004 70200 333 70000="
"94733099999","2019-01-05T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","200,1,N,0026,1","99999,9,9,N","000100,1,9,9","+0209,1","+0193,1","99999,9","24,0004,3,1",,"1,1,02,1","1,1,02,1","08,99,1,99,9,99,9,99999,9,99,9,99,9","51,1","SYN05294733 11/01 82005 10209 20193 69944 75111 333 70004="
"94733099999","2019-01-08T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","070,1,N,0026,1","22000,1,9,N","025000,1,9,9","+0344,1","+0213,1","99999,9","06,0000,9,1",,"2,1,02,1","2,1,02,1","04,99,1,99,9,99,9,99999,9,99,9,99,9","02,1","SYN04294733 11/75 40705 10344 20213 60001 70222="
"""  # noqa: E501

모두 좋은 답변입니다만, 「암묵적으로 연결된」스트링의 편집에 도움이 되는 에디터 플러그 인을 찾을 수 없었기 때문에, 간단하게 패키지를 작성했습니다.

pip(단락 설치)에서 이 오래된 스레드를 배회하는 사람이 있는지 확인합니다.html과 같이 여러 줄 문자열을 포맷합니다(공백 압축, 새 단락의 경우 두 줄 추가, 줄 사이의 공백 걱정 없음).

from paragraphs import par


class SuddenDeathError(Exception):
    def __init__(self, cause: str) -> None:
        self.cause = cause

    def __str__(self):
        return par(
            f""" Y - e - e - e - es, Lord love you! Why should she die of
            {self.cause}? She come through diphtheria right enough the year
            before. I saw her with my own eyes. Fairly blue with it, she
            was. They all thought she was dead; but my father he kept ladling
            gin down her throat till she came to so sudden that she bit the bowl
            off the spoon. 

            What call would a woman with that strength in her have to die of
            {self.cause}? What become of her new straw hat that should have
            come to me? Somebody pinched it; and what I say is, them as pinched
            it done her in."""
        )


raise SuddenDeathError("influenza")

...가 되다.

__main__.SuddenDeathError: Y - e - e - e - es, Lord love you! Why should she die of influenza? She come through diphtheria right enough the year before. I saw her with my own eyes. Fairly blue with it, she was. They all thought she was dead; but my father he kept ladling gin down her throat till she came to so sudden that she bit the bowl off the spoon.

What call would a woman with that strength in her have to die of influenza? What become of her new straw hat that should have come to me? Somebody pinched it; and what I say is, them as pinched it done her in.

모든 것이 쉽게 (Vim) 'gq'로 정렬됩니다.

백슬래시:

s = "this is my really, really, really, really, really, really" +  \
    "really long string that I'd like to shorten."

또는 패런으로 감습니다.

s = ("this is my really, really, really, really, really, really" + 
    "really long string that I'd like to shorten.")

사용 가능한 옵션:

  • 백슬래시:"foo" \ "bar"
  • 플러스 기호 뒤에 백슬래시:"foo" + \ "bar"
  • 괄호:
    • ("foo" "bar")
    • 플러스 기호가 있는 괄호:("foo" + "bar")
    • PEP8, E502: 백슬래시는 브래킷 사이에 용장성이 있습니다.

피하다

("foo", "bar")태플을 정의합니다.


>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
>>> s = ("a" + 
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> 

검정 [https://github.com/psf/black]을 사용하여 이렇게 포맷합니다.

   help=f"""filters, lista de filtros para cargar las base de conocimiento.
   Pueden mandarse solo algunos filtros ya que no son obligatorios,
   por ejemplo, si no se manda sts, se cargarán todos las bases de todos los estados.""",

\을 사용하다

s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."

작동해야 합니다.

큰 문자열을 지정할 때는 여기에 기재되어 있지 않은 몇 가지 방법을 사용하는 경향이 있습니다만, 이것은 매우 구체적인 시나리오입니다.YMMV...

  • 여러 줄의 텍스트 블럽(대부분 서식화된 토큰 포함):

    error_message = '''
    I generally like to see how my helpful, sometimes multi-line error
    messages will look against the left border.
    '''.strip()
    
  • 원하는 문자열 보간 방법을 사용하여 변수를 하나씩 확장합니다.

    var = 'This is the start of a very,'
    var = f'{var} very long string which could'
    var = f'{var} contain a ridiculous number'
    var = f'{var} of words.'
    
  • 파일에서 읽어보세요.PEP-8은 파일 내의 문자열 길이를 제한하지 않고 코드 행만 제한합니다.:)

  • bluet-force 또는 에디터를 사용하여 새 행을 사용하여 문자열을 관리 가능한 행으로 분할한 다음 새 행을 모두 삭제합니다.(처음 기재한 기법과 유사)

    foo = '''
    agreatbigstringthatyoudonotwanttohaveanyne
    wlinesinbutforsomereasonyouneedtospecifyit
    verbatimintheactualcodejustlikethis
    '''.replace('\n', '')
    
message = f"Variable : child({type(child)}) -> is not of"\
        " type Node."

이 구문은 나에게 효과가 있었다.두 번째 문장의 들여쓰기를 주의해 주세요.올바른 들여쓰기가 필요합니다.

저는 예전에 textwrap.dedent를 사용한 적이 있습니다.조금 번거롭기 때문에 지금은 줄 바꿈이 좋지만, 꼭 블록 들여쓰기를 원하신다면 좋다고 생각합니다.

코드 예(슬라이스를 사용하여 첫 번째 '\n'을 제거하는 트림):

import textwrap as tw
x = """\
       This is a yet another test.
       This is only a test"""
print(tw.dedent(x))

설명:

dedent는 새 줄 앞에 있는 텍스트의 첫 번째 줄에 있는 공백을 기준으로 들여쓰기를 계산합니다.조정하고 싶은 경우는, 다음의 방법으로 간단하게 재실장할 수 있습니다.re모듈.

이 방식에는 여전히 매우 긴 행이 필요한 것보다 길 수 있다는 제한이 있으며, 이 경우 문자열을 연결하는 다른 방식이 더 적합합니다.

언급URL : https://stackoverflow.com/questions/1874592/how-to-write-very-long-string-that-conforms-with-pep8-and-prevent-e501

반응형