[Python] Keyword란? (Soft Keyword 포함)

2023. 6. 11. 17:19·Programming
728x90
728x90

Keywords (or Reserved Words)

Keyword란 Python에서 특별한 단어 (special word)들을 가르킨다.

  • Keyword들은 Python에서 특정한 목적으로 사용되도록 이미 정해진 word들로
  • Python에서 정해놓은 방법 외로는 사용을 할 수 없음.
  • 때문에 variable이나 function등의 name 등으로 사용할 수 없음.

 

다음 code는 keyword 여부를 체크해볼 수 있는 keyword module을 사용하는 예제임.

import keyword

# string argument가 Python Keyword인지를 True/False 로 반환해줌.
print(f'None is a keyword of Python Interpreter. : {keyword.iskeyword("None")}')

# Python Interpreter에서 정의된 python keyword들을 keyword.kwlist라는 sequence가
# 가지고 있음.
print(keyword.kwlist)

다음은 Python Interpreter가 특정용도로 사용하기로 정해진 Keyword들의 리스트임.

'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 
'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 
'return', 'try', 'while', 'with', 'yield'

https://docs.python.org/ko/3/library/keyword.html

 

keyword — Testing for Python keywords

Source code: Lib/keyword.py This module allows a Python program to determine if a string is a keyword or soft keyword.

docs.python.org


Soft Keywords

Python 3.10 이후로 보이는 soft keywords라는 개념은 특정한 context(맥락) 등에서 keyword로 동작하는 word들을 가르킴.

 

예를 들어 match나 case 는 match compound statement의 context에선 keywords로 처리된다.

하지만 해당 context 밖에선 variable 이나 function의 name으로 사용이 가능함.

  • keyword.issoftkeyword(s)는 keyword.iskeyword(s)에 대응하고,
  • keyword.softkwlist는 keyword.kwlist에 대응함.

다음 예는 match 사용예임.

import sys

def get_platform():
  ret_val = None
  match sys.platform:
    case "windows":
      ret_val = "Running on Windows!"
    case "darwin":
      ret_val = "Running on MacOS!"
    case "linux":
      ret_val = "Running on Linux!"
    case _:
      raise NotImplementedError(
          f"{sys.platform} is currently not supported"
      )
  return ret_va
  
match = get_platform()
print(match)

import keyword

print('keyowrd check!',keyword.iskeyword('match'))
print('softkeyowrd check!',keyword.issoftkeyword('match')
  • match가 match context 밖에선 keyword가 아니므로 variable name이 될 수 있음.

더 읽어보면 좋은 자료들

https://gist.github.com/dsaint31x/c3258cf0609ce80810ee5194c46e502c

 

py_keywords_soft_keywords.ipynb

py_keywords_soft_keywords.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

'Programming' 카테고리의 다른 글

[Python] Python 소개?  (0) 2023.06.12
[Python] Dynamic Typed Language vs. Static Typed Language  (0) 2023.06.11
[Python] Comments and Docstrings  (0) 2023.06.11
[Basic] namespace, frame, and context  (0) 2023.06.11
[Python] Function Call (함수호출)  (0) 2023.06.10
'Programming' 카테고리의 다른 글
  • [Python] Python 소개?
  • [Python] Dynamic Typed Language vs. Static Typed Language
  • [Python] Comments and Docstrings
  • [Basic] namespace, frame, and context
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (748)
      • Private Life (13)
      • Programming (56)
        • DIP (112)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    signal_and_system
    Probability
    signals_and_systems
    Convolution
    cv2
    SS
    math
    Term
    opencv
    Python
    function
    DIP
    linear algebra
    Optimization
    SIGNAL
    인허가제도
    fourier transform
    Programming
    Vector
    numpy
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] Keyword란? (Soft Keyword 포함)
상단으로

티스토리툴바