본문으로 바로가기
반응형


Using type() to compare types

isinstance 함수는 상속도 지원하기 때문에 타입을 검사할 때 최적화된 함수이다.

따라서 타입 검사가 필요할때는 isinstance()를 사용해야한다.


Anti-pattern

import types

class Rectangle(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

r = Rectangle(3, 4)

# bad
if type(r) is types.ListType:
    print("object r is a list")

위 예제에서는 if문을 통해 Rectangle 클래스가 ListType 타입인지 검사한다.

이러한 스타일은 권장되는 패턴이라고 볼 수 없다.


import types

class Rectangle(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

class Circle(object):
    def __init__(self, radius):
        self.radius = radius

c = Circle(2)
r = Rectangle(3, 4)

# bad
if type(r) is not type(c):
    print("object types do not match")

위 코드또한 에러를 발생시키지는 않지만 같은 형태이다.


Best practice

import types

class Rectangle(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height

r = Rectangle(3, 4)

# good
if isinstance(r, types.ListType):
    print("object r is a list")

따라서 이처럼 isinstance 함수를 통해 타입을 검사하는 방법이 좋다.


출처 : https://docs.quantifiedcode.com/python-anti-patterns/readability/do_not_compare_types_use_isinstance.html

반응형