Skip to content

Use of __new__ in CharField makes it impossible to subclass CharField #303

@mxfunc

Description

@mxfunc

Hello,

Please correct me if I am making a mistake. But this is my observation. I subclassed CharField and added a custom parameter like this:

class ISBN10Field(CharField):
    default_validators = [ISBN10Validator]
    length = 10
    normalize: bool

    def __init__(self, normalize: bool = True, *args, **kwargs):
        self.normalize = normalize
        if self.normalize:
            kwargs["max_length"] = self.length
        super().__init__(*args, **kwargs)


field = ISBN10Field(normalize=False)
print(field.length)

Two issues:
Because of __new__ method, the type of field is always CharField[str] and not ISBN10Field. That causes attribute validation to fail. Also, because of overload, adding new parameters gives errors. The last two lines generate the following errors:

tests.py:38:12 - error: No overloads for "__new__" match the provided arguments
    Argument types: (Literal[False]) (reportCallIssue)

tests.py:68:32 - error: Cannot access attribute "length" for class "CharField[str]"
    Attribute "length" is unknown (reportAttributeAccessIssue)

Any ideas on how to fix this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions