Skip to content

cmping fails when attrib is a numpy array #435

@meereeum

Description

@meereeum

The generated cmp methods fail if the attrib is a numpy array (of size >1) with

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

this is because:

# equivalent to how __eq__compares fields:
(np.array([47,47],) == (np.array([47,47],) # ValueError
# vs:
(np.array([47,47]) == np.array([47,47])).all() # True

I realize that this can be switched off with cmp=False, but often comparing these attribs is useful!

reproducible example:

@attr.s(auto_attribs=True)
class A:
    arr: np.ndarray

foo = A(np.array([47,47]))
bar = A(np.array([47,47]))

foo == bar # ValueError

the simplest fix might be to trust user annotations about what is/isn't a numpy array and check those separately. or, maybe better, would be awesome to supply a custom cmp function, e.g.

@attr.s
class A:
    arr: np.ndarray = attr.ib(cmpf=lambda f,x,y: f(x,y).all())

where f is the standard cmp function (eq, lt, etc) and x,y are the items being compared.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions