ㅁㄴㅇㄻㄴㅇㄹ

TypeError: 'property' object is not iterable 본문

Python

TypeError: 'property' object is not iterable

hanbin8269 2021. 6. 2. 13:38
import peewee

class MySQLModel(peewee.Model):
    @property
    @classmethod
    def unique_fields(cls) -> list:
        for field_name in cls._meta.fields.keys():
            field = getattr(cls, field_name)
            if field.unique == True or field.primary_key == True:
                yield field

peewee 모델의 unique한 field의 이름을 iterable한 객체로 반환하는 property 함수를 만들었다.

key in [field.name for field in MySQLModel.unique_fields]

그런데 위와 같이 사용 할 때 TypeError: 'property' object is not iterable 에러가 발생했다.

해결방법을 찾아보니 metaclass에서 property 함수를 만드는 방법, class decorator를 직접 만들어서 처리하는 방법 등이 있었다.

class decorator를 직접 만들어서 처리하는 방법은 아래와 같은데, 이게 마음에 들었다.


class classproperty(object):
    def __init__(self, function):
        self.function = function

    def __get__(self, owner_self, owner_cls):  # classproperty 객체에 접근할 때 inner_func 결과값을 반환하도록
        return self.function(owner_cls)


class MySQLModel(peewee.Model):
    @classproperty
    def unique_fields(cls) -> list:
        for field_name in cls._meta.fields.keys():
            field = getattr(cls, field_name)
            if field.unique == True or field.primary_key == True:
                yield field