AndreaCensi/contracts

When declaring a class, I cannot refer to the class in a contract...?

Opened this issue · 4 comments

The following code doesn't work:

class CommodityType(object):
    """
    A generic commodity type.
    """
    def __init__(self, symbol):
    self.symbol = symbol

    # @contract(other=CommodityType)
    def __eq__(self, other):
    return self.symbol == other.symbol

It complains that CommodityType is not defined. Is there any way around this problem? I was trying to avoid having an isinstance check inside.

Thanks,

No, this is a limitation of Python. You cannot refer to the class being
defined.

On Saturday, February 14, 2015, beetleb notifications@github.com wrote:

The following code doesn't work:

class CommodityType(object):
"""
A generic commodity type.
"""
def init(self, symbol):
self.symbol = symbol

# @contract(other=CommodityType)
def __eq__(self, other):
return self.symbol == other.symbol

It complains that CommodityType is not defined. Is there any way around
this problem? I was trying to avoid having an isinstance check inside.

Thanks,


Reply to this email directly or view it on GitHub
#34.

(sent from mobile device, please pardon typos and brevity)

I'm leaving this open, because we need to find some workaround, as this is a very common case.

I'm still not sure about this could be implemented. It seems it is a limitation of Python and the workaround would be very complicated. We would need to defer the evaluation of the contracts.

I believe SQLAlchemy shares this issue and they resolve it by using strings.

That is, this..

class CommodityType(object):
    """
    A generic commodity type.
    """
    def __init__(self, symbol):
         self.symbol = symbol

    @contract(other=CommodityType)
    def __eq__(self, other):
        return self.symbol == other.symbol

..would become

class CommodityType(object):
    """
    A generic commodity type.
    """
    def __init__(self, symbol):
         self.symbol = symbol

    @contract(other='CommodityType')
    def __eq__(self, other):
        return self.symbol == other.symbol