Python : 들여 쓰기에 4 개의 공백을 사용합니다. 왜?
파이썬을 코딩하는 동안 들여 쓰기에 2 개의 공백 만 사용하고 있지만 PEP-8은 실제로 4 개의 공백을 권장하지만 역사적으로보기 드문 경우입니다.
그래서 누구든지 2 대신 4 공백을 사용하도록 설득 할 수 있습니까? 장단점은 무엇입니까?
추신 그리고 마지막으로, 기존의 모든 코드베이스를 2 개의 공백에서 4 개의 공백으로 변환하는 쉬운 방법은 무엇입니까?
PPS PEP-8 또한 들여 쓰기에 탭을 사용하지 않는 것이 좋습니다. 여기에서 읽으십시오
요약하면 다음과 같습니다.
장점 :
- 80 줄 이상의 줄을 감을 때 더 많은 공간을 확보하십시오.
- 스 니펫에서 코드를 복사 할 수 있으며 작동합니다.
단점 :
- 더 깊은 수준의 중첩 된 문을 사용하면 실제 코드를위한 공간이 줄어 듭니다.
감사.
다른 사람은 모두 4 칸을 사용합니다. 그것이 내가 만나서 받아 들인 4 개의 공간을 사용하는 유일한 이유입니다. 내 마음 속에서 나는 여전히 탭을 사용하고 싶다 (들여 쓰기 당 1 개의 들여 쓰기 문자, 말이 안 되는가? 다른 공백과 들여 쓰기를 분리하라. 나는 탭이 다른 폭 으로 표시 될 수있어 구문 상 차이가없는 것은 상관하지 않는다 . 최악의 경우 그럴 수있는 것은 댓글 중 일부가 정렬되지 않는다는 것입니다. 공포!)하지만 저는 파이썬 커뮤니티 전체가 4 개의 공백을 사용하기 때문에 4 개의 공백을 사용한다는 사실을 받아 들였습니다. 이렇게하면 다른 사람들이 작성한 코드 조각에서 코드를 조합 할 수 있으며 모든 것이 작동합니다.
def + 1 개의 공백은 4 개의 문자를 만들기 때문에 4 개의 공백 문자가 함수의 내부 코드를 멋지게 들여 쓰기한다는 사실이 마음에 듭니다.
def·foo():
····pass
진짜 질문은 왜 탭이 아니라 공백인지라고 생각합니다.
탭이 분명히 더 좋습니다.
- 일관되지 않은 들여 쓰기를하는 것은 거의 불가능합니다. (일반적으로 4 개의 공백 들여 쓰기가있는 코드를 보았지만 일부 부분은 한 공백으로 표시됩니다. 간단한 검사로 공백이 7 개 또는 8 개 있는지 확인하기가 어렵습니다. 탭 스톱을 1 칸으로 설정하지 않으면 탭에서 발생하지 않습니다.)
- Tab은 들여 쓰기에 대한 논리적 의미 표현이며, 다른 사람의 선호도를 훼손하지 않고 원하는만큼의 "공백"(또는 열) 을 표시 하도록 선택할 수 있습니다 .
- 손에 "메모장"(또는 다른 더미 편집기) 만 있으면 키 입력 이 적습니다 .
- 탭 추가 및 제거는 대칭 작업입니다. 대부분의 IDE는 탭 키를 눌렀을 때 자동으로 4 개의 공백을 삽입 할 수 있지만 일반적으로 백 스페이스를 눌렀을 때 1 개의 공백 만 제거합니다 (내어 쓰기 작업은 여전히 shift-tab으로 액세스 할 수 있지만 두 개의 키 조합입니다) 또는 마우스를 사용하여 클릭 들여 쓰기 중간에 한 문자를 삭제합니다.
- 4 개가 아닌 1 바이트 만 사용합니다 (수천 줄을 곱하면 몇 KB를 절약 할 수 있습니다! : p).
- 합의를 결정할 것이 하나 더 적습니다. 왜냐하면 공간을 선택하기로 결정하면 토론이 다시 시작되어 몇 개인 지 선택하기 때문입니다 (합의가 약 4 인 것처럼 보임에도 불구하고).
공간의 장점 :
- 귀도는 그들을 좋아합니다.
- 여기에 탭을 쉽게 입력 할 수는 없지만 포커스를 이동합니다 (붙여 넣을 수 있음).
"더 나은"들여 쓰기가 없습니다. 종교적인 성전 주제입니다. Four는 들여 쓰기를 명확하게하기에 충분하지만 전체 화면이 대부분 공백이고 프로그램의 절반을 읽으려면 가로로 스크롤해야하기 때문에 좋습니다.
또한 "탭"의 역사적 정의에 대한 "하프 탭"이라는 장점도 있습니다.
그 외에는 그룹이 좋아하는 것을 사용하십시오. 초콜렛 대 바닐라 같아요.
쉽게 전환하는 방법은 탭 및 스페이스 탭을 지원하는 편집기를 사용하는 것입니다. 모든 선행 스페이스 탭을 탭으로 변환하고 탭 크기를 4로 설정 한 다음 선행 탭을 다시 스페이스 탭으로 변환합니다.
파이썬 스크립트로도 매우 쉽습니다. 모든 선행 공백을 세고 줄의 시작 부분에 같은 양을 추가하고 다시 작성하십시오.
PEP는 당신의 보스가 아닙니다. 이미 일관되게 2 칸 들여 쓰기 된 경우이를 준수하기 위해 모든 코드를 변경할 이유가 없습니다. 정말로 그렇게 중요하다고 생각한다면 앞으로 나아갈 수는 있지만 솔직히 나는 그렇지 않습니다. 읽기와 쓰기 모두에서 당신과 동료들에게 가장 편안함을 제공하는 컨벤션을 사용하는 것이 좋습니다.
괜찮은 편집기 (emacs, vim)는이 모든 말도 안되는 소리를 추상화합니다. 공백이나 탭에서도 똑같이 잘 작동하며 임의의 수의 공백 (또는 탭 문자에 대해 임의의 수의 공백 너비)을 사용하도록 구성 할 수 있습니다. 또한 별다른 문제없이 서로 다른 형식간에 변환 할 수 있습니다 ( :retab
vim 의 명령 참조 ).
소스 서식을 대량으로 변환하려는 경우 들여 쓰기 유틸리티를 살펴 보는 것이 좋습니다 .
즉, 다른 질문에 대답하는 것을 거부 할 수 없습니다. 전체 문제를 우회하고 모든 사람이 원하는대로 설정된 너비로 소스 코드를 볼 수 있기 때문에 제 선호는 항상 탭이었습니다. 또한 변환에 도움이되지 않는 편집기에서 작업 할 때 타이핑이 훨씬 적습니다. 2 대 4 공간에 관해서는 순전히 미용입니다.
또한 이유 중 하나는 긴 줄 (80 개 이상의 기호)이 있고이를 2 개로 나누고 자 할 때 들여 쓰기 할 공백이 1 개뿐이므로 약간 혼란 스럽습니다.
if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
and someotherstatementhere:
# some code inside if block
pass
if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
and someotherstatementhere:
# some code inside if block
pass
If you're the only coder working on your source file and there are no coding standards that enforce a particular style, use whatever you're comfortable with. Personally (and in line with our coding standard), I use hard tabs so that whoever is looking at the code can use their own preference.
To make a change, you simply need to change all start-of-line spaces to ones that are twice as large. There are many ways to do this; in the Vim text editor, I can think of two: firstly:
:%s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)
This is a simple regular expression that looks for one or more pairs of spaces at the start of the line and replaces them with twice as many spaces as were found. It can be extended to do all files by opening vim with:
vim *.py
(or the equivalent), followed by (untested):
:argdo %s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)/ | w
Alternatively:
" Switch to hard tabs:
:set noexpandtab
" Set the tab stop to the current setting
:set tabstop=2
" Change all spaces to tabs based on tabstop
:retab!
" Change the tab stop to the new setting
:set tabstop=4
" Go back to soft tabs
:set expandtab
" Replace all the tabs in the current file to spaces
:retab
Of course, many other tools will offer similar features: I would be surprised if something like sed
, awk
, perl
or python
couldn't do this very easily.
Identation and general coding style standards vary from language to language, project to project. There is one reason for adopting a coding style standard: so that the code look uniform, no matter who wrote it. That improves legibility in the project, and, to put it bluntly, it looks better.
There is one reason that is not valid when adopting a coding style standard: because you like it. Coding standards exists precisely because people's preferences vary, and if left to their own, chaos would ensue, to the detriment of all.
If you are writing code for yourself alone, which no one will ever read, go ahead and write it whatever you like. Otherwise, following the accepted standard of your community will make your code much more agreeable to everyone else's eyes. And remember, too, that if you DO decide to contribute code to a community in the future, you'll have an easier time if you are used to their coding style already.
As for changing the tab size, there are are many source code formatters out there which support Python, and most programmer's editors and IDEs also have this capability. You probably have it already, it's just a matter of consulting the documentation for the editor you are using.
One reason is that if you use less spaces for indentation, you will be able to nest more statements (since line length is normally restricted to 80).
Now I'm pretty sure that some people still disagree on how many nested constructs should be the maximum.
It is easier to visually identify long nested code blocks with 4 spaces. Saves time when debugging.
If you want to write python code together with other programmers it becomes a problem if you use a different indention as them. Most Python programmers tend to use 4-space indention.
using 4 spaces or 2 spaces is entirely up to you. 4 spaces is just a convention. What is most important, don't mix tabs and spaces. Use the space bar
참고URL : https://stackoverflow.com/questions/1125653/python-using-4-spaces-for-indentation-why
'programing tip' 카테고리의 다른 글
Xcode 전체 스택 추적 (0) | 2020.11.06 |
---|---|
LINQ를 사용하여 문자열을 정수 배열로 변환 (0) | 2020.11.06 |
iOS-Xcode 9에서 정의로 이동하기위한 바로 가기? (0) | 2020.11.06 |
작업 복사본 잠김 (0) | 2020.11.06 |
플롯을 PDF로 저장 (0) | 2020.11.06 |