contracts icon indicating copy to clipboard operation
contracts copied to clipboard

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

Open beetleb opened this issue 10 years ago • 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,

beetleb avatar Feb 14 '15 05:02 beetleb

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

On Saturday, February 14, 2015, beetleb [email protected] 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 https://github.com/AndreaCensi/contracts/issues/34.

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

AndreaCensi avatar Feb 14 '15 14:02 AndreaCensi

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

AndreaCensi avatar Feb 14 '15 20:02 AndreaCensi

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.

AndreaCensi avatar Jun 02 '15 20:06 AndreaCensi

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

timClicks avatar Jul 17 '16 23:07 timClicks