Nice programing

파이썬에서 변수 유형을 주장하는 적절한 방법

nicepro 2020. 12. 25. 22:55
반응형

파이썬에서 변수 유형을 주장하는 적절한 방법


함수를 사용할 때 변수의 유형이 예상대로인지 확인하고 싶습니다. 그것을 올바르게하는 방법?

다음은 역할을 수행하기 전에이 작업을 수행하려는 가짜 함수의 예입니다.

def my_print(begin, text, end):
    """Print 'text' in UPPER between 'begin' and 'end' in lower

    """
    for i in (begin, text, end):
        assert isinstance(i, str), "Input variables should be strings"
    out = begin.lower() + text.upper() + end.lower()
    print out

def test():
    """Put your test cases here!

    """
    assert my_print("asdf", "fssfpoie", "fsodf")
    assert not my_print("fasdf", 33, "adfas")
    print "All tests passed"

test()

올바른 접근 방식을 주장합니까? 대신 try / except를 사용해야합니까?

또한 내 주장 테스트 세트가 제대로 작동하지 않는 것 같습니다.

감사합니다 pythoneers


isinstance내장 당신이 정말로해야 할 경우 선호하는 방법이지만, 더 나은 파이썬의 모토를 기억하는 것입니다 : "그것은 권한보다 용서를 물어 쉽게"-) (실제로 그레이스 머레이 호퍼의 좌우명 ;-)했다!. 즉 :

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

이것은 BTW를 통해 추가 노력없이 유니 코드 문자열에서 함수가 잘 작동하도록합니다!-)


Python 2.6 버전에 대해이 예제를 시도해 볼 수 있습니다.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + begin.upper() + end.lower()

그러나 대신 함수가 자연스럽게 실패하도록 고려한 적이 있습니까?


이렇게이 type('')효과적으로 동등 str하고types.StringType

따라서 type('') == str == types.StringType" True"로 평가됩니다.

이런 식으로 유형을 검사하면 ASCII 만 포함 된 유니 코드 문자열은 실패하므로 assert type(s) in (str, unicode)또는 같은 작업을 수행 할 수 있습니다.이 assert isinstance(obj, basestring)중 후자는 007Brendan의 주석에서 제안되었으며 아마도 선호 될 것입니다.

isinstance() 객체가 클래스의 인스턴스인지 묻고 싶을 때 유용합니다. 예 :

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

그러나 기본 유형, 예를 들어 대한 str, unicode, int, float, long요구 등 type(var) == TYPE의 뜻 작업 확인을.

참조 URL : https://stackoverflow.com/questions/2589522/proper-way-to-assert-type-of-variable-in-python

반응형