티스토리 뷰

파이썬

[python] assert 문 처리

글을 쓰는 개발자 2021. 8. 4. 15:51
반응형

assert문을 알게 된 계기

def get_queryset(self):
        """
        Get the list of items for this view.
        This must be an iterable, and may be a queryset.
        Defaults to using `self.queryset`.
        This method should always be used rather than accessing `self.queryset`
        directly, as `self.queryset` gets evaluated only once, and those results
        are cached for all subsequent requests.
        You may want to override this if you need to provide different
        querysets depending on the incoming request.
        (Eg. return a list of items that is specific to the user)
        """
        assert self.queryset is not None, (
            "'%s' should either include a `queryset` attribute, "
            "or override the `get_queryset()` method."
            % self.__class__.__name__
        )

        queryset = self.queryset
        if isinstance(queryset, QuerySet):
            # Ensure queryset is re-evaluated on each request.
            queryset = queryset.all()
        return queryset

DRF 코드를 보는데 해당 assert라는 단어를 보게 되는데 이걸 왜 쓸까? 라는 생각을 하게 되었다.

우선 파이썬은 자바나 c언어 처럼 변수가 정해져 있지 않은 언어라는 점에서 assert문을 쓰게 되었을 때 해당 작업을 제대로 할 수 있다는 것에서 큰 이점을 가지게 된다. 

이렇게 assert문을 쓰게 되면 데이터를 보증할 수 있다는 것에서 큰 에러를 일으키지 않고 작동할 수 있게 된다.

 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함