본문 바로가기
TIL (Today I Learned)/Python

[Python] 식별자 이름 짓는 방법

by 둥굴프 2023. 3. 29.
파이썬에 대한 기본적인 이해를 위해 작성했습니다.

 

식별자(Identifier)의 이름을 짓는 것은 특정 룰을 따라야만 한다. 또한 특정 컨벤션을 따라야 한다.

 

따라야만 하는 룰(Must)

start with underscore ( _ ) or letter ( a-z A-Z )

followed by number of underscores ( _ ), letters ( a-z A-Z ), or digits ( 0-9 )

 

cannot be reserved words (예약어 사용 불가능):

None, True, False,

and, or, not,

if, else, elif,

for, while, break, continue, pass,

def, lambda, global, nonlocal, return, yield,

del, in, is, assert, class,

try, expect, finally, raise,

import, from, with, as

 

따라야 하는 컨벤션(Conventions)

_my_var : single underscore

This is a convention to indicate "internal use" or "private" objects

파이썬에는 private이라는 개념이 없다.

그렇기 때문에, 개발자들끼리 약속을 하여 변수명을 지정한다.

해당 인식자가 선언된 모듈을 from module import * 와 같이 불러온다면 어떻게 될까? 

single underscore로 명시된 인식자는 불러올 수 없다.

왜냐하면, Python 인터프리터는 private 객체라는 것을 인식할 수 있기 때문에 불러오지 않는다.

접근이 불가능한 것은 아니다. 위의 방식과 다르게 불러오면 접근가능하다.

 

__my_var : doubled underscore

Used to "mangle" class attributes - useful in inheritance chains

참고블로그 : https://devbruce.github.io/python/py-30-class_mangling/

 

__my_var__ : doubled underscore

Used for system-defined names that have a special meaning to the interpreter

시스템으로 정의된 이름이다.

파이썬에 이미 정의된 것만 사용해야 한다. 이런 식으로 이름을 정하면 안 된다!

다음과 같은 것들이 있다.

__init__

x < y → x.__lt__(y)

 

PEP 8 Style Guide

필수적으로 따라야 하는 컨벤션이 아니다. 코드 안에서 일관성을 지킬 수 있으면 된다.

참고자료 : https://peps.python.org/pep-0008/

참고블로그 : https://spoqa.github.io/2012/08/03/about-python-coding-convention.html

 

Packages : short, all-lowercase names. Preferably no underscores. utilities

Modules : short, all-lowercase names. Can have underscores. db_utiles or dbutils

Classes : CapWords (upper camel case) convention. BankAccount

Function : lowercase, words separated by underscores (snake_case) open_account

Variables : lowercase, words separated by underscores (snake_case) account_id

Constants : all-uppercase, words separated by underscores. MIN_APR

'TIL (Today I Learned) > Python' 카테고리의 다른 글

[Python] While loop  (0) 2023.04.02
[Python] Function  (0) 2023.03.29
[Python] ternary operator  (0) 2023.03.29
[Python] NEWLINE  (0) 2023.03.28
[Python] Python Types  (0) 2023.03.28

댓글