본문 바로가기

개발하자

Python: 값 유형별 일치/대소문자 수

반응형

Python: 값 유형별 일치/대소문자 수

파이썬 3.10에서 새로운 / 구문을 사용하다가 이상한 문제를 발견했습니다. 다음 예제는 작동해야 하는 것처럼 보이지만 오류를 발생시킵니다:

values = [
    1,
    "hello",
    True
]

for v in values:
    match type(v):
        case str:
            print("It is a string!")
        case int:
            print("It is an integer!")
        case bool:
            print("It is a boolean!")
        case _:
            print(f"It is a {type(v)}!")
$ python example.py
  File "/.../example.py", line 9
    case str:
         ^^^
SyntaxError: name capture 'str' makes remaining patterns unreachable
  • 첫 번째 경우(값)는 항상 결과로 나타날 것임을 언급하고 있다.

타입을 문자열로 변환하는 것 외에 이것에 대한 대안이 있는지 궁금합니다.




일치하지 말고 직접 일치시키십시오:

values = [
    1,
    "hello",
    True,
]

for v in values:
    match v:
        case str():
            print("It is a string!")
        case bool():
            print("It is a boolean!")
        case int():
            print("It is an integer!")
        case _:
            print(f"It is a {type(v)}!")

의 인스턴스가 되는 것이 문제를 일으키지 않도록 주문과 여기의 순서를 바꾸었습니다.

이것은 성냥이다.




따옴표

값 = [ False, "hello", True ]

vin 값의 경우: match type(v): case 'str': print("It is string!") case 'int': print("It is intergent!") case 'boole': print("It is boolean!") case _: print(f"It is a {type(v)!"))


반응형