Skip to content

Define defaults for subclass that uses validator of parent class? #1259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
my1e5 opened this issue Mar 13, 2024 · 1 comment
Closed

Define defaults for subclass that uses validator of parent class? #1259

my1e5 opened this issue Mar 13, 2024 · 1 comment

Comments

@my1e5
Copy link
Contributor

my1e5 commented Mar 13, 2024

I am trying to create subclasses of a parent class which have their own default values but use the validator defined in the parent class. Is this possible? Here is a simple working example:

from attrs import define, field, validators

@define(kw_only=True)
class Vehicle:
    num_wheels: int = field(validator=validators.instance_of(int))

    @num_wheels.validator
    def validate_num_wheels(self, attribute, value) -> None:
        if value <= 0:
            raise ValueError("Must be greater than 0")

And here are some subclasses which I know don't work - but hopefully illustrate what I want to do.

@define
class Car(Vehicle):
    num_wheels: int = field(default=4) #! This doesn't work


@define
class Motorbike(Vehicle):
    @num_wheels.default #! This doesn't work either
    def default_num_wheels(self) -> int:
        return 2

I basically want to protect against a user doing Car(num_wheels=3.14) or Car(num_wheels=-1) accidently. And also have this work for Motorbike etc. But I want Car() and Motorbike() to return default values defined in the subclass. Is this possible?

@my1e5 my1e5 changed the title Define defaults for subclass that use validator of parent class? Define defaults for subclass that uses validator of parent class? Mar 13, 2024
@hynek
Copy link
Member

hynek commented Mar 14, 2024

I have answered in https://stackoverflow.com/a/78158263/476759 – tl;dr: #637, but you might get around it.

@hynek hynek closed this as not planned Won't fix, can't repro, duplicate, stale Mar 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants