{"record":{"id":"75fcb7462253ff5b","repo":"pola-rs/polars","slug":"enum-categories-must-be-unique-found-duplicate-d","errorCode":null,"errorMessage":"Enum categories must be unique; found duplicate {duplicate!r}","messagePattern":"Enum categories must be unique; found duplicate (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/classes.py","lineNumber":1038,"sourceCode":"        elif not isinstance(categories, pl.Series):\n            categories = pl.Series(values=categories)\n\n        if categories.is_empty():\n            self.categories = pl.Series(name=\"category\", dtype=String)\n            return\n\n        if categories.has_nulls():\n            msg = \"Enum categories must not contain null values\"\n            raise TypeError(msg)\n\n        if (dtype := categories.dtype) != String:\n            msg = f\"Enum categories must be strings; found data of type {dtype}\"\n            raise TypeError(msg)\n\n        if categories.n_unique() != categories.len():\n            duplicate = categories.filter(categories.is_duplicated())[0]\n            msg = f\"Enum categories must be unique; found duplicate {duplicate!r}\"\n            raise ValueError(msg)\n\n        self.categories = categories.rechunk().alias(\"category\")\n\n    def __eq__(self, other: PolarsDataType) -> bool:  # type: ignore[override]\n        # allow comparing object instances to class\n        if type(other) is DataTypeClass and issubclass(other, Enum):\n            return True\n        elif isinstance(other, Enum):\n            return self.categories.equals(other.categories)\n        else:\n            return False\n\n    def __hash__(self) -> int:\n        return hash((self.__class__, tuple(self.categories)))\n\n    def __repr__(self) -> str:\n        class_name = self.__class__.__name__\n        return f\"{class_name}(categories={self.categories.to_list()!r})\"","sourceCodeStart":1020,"sourceCodeEnd":1056,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/classes.py#L1020-L1056","documentation":"Validation when constructing an Enum dtype: after converting categories to a Series, uniqueness is checked via n_unique vs len; a duplicated category would make the enum's category mapping ambiguous, so construction raises. Provide a list/Series of distinct non-null strings.","triggerScenarios":"pl.Enum(pl.Series(['a', 'b', 'a'])); deriving categories with duplicates from raw data without .unique(); string enum classes with two members sharing the same value.","commonSituations":"Hand-assembled category lists from merged sources; Python enums with aliases (two names, one value) flattened to duplicates.","solutions":["Call .unique() on the Series before passing it: pl.Enum(categories.unique())","Use sorted(set(values)) for plain iterables","Deduplicate enum aliases or pass the alias-free values explicitly"],"exampleFix":"// before\npl.Enum(pl.Series(['a', 'b', 'a']))\n// after\npl.Enum(pl.Series(['a', 'b', 'a']).unique())","handlingStrategy":"validation","validationCode":"series = pl.Series(values) if not isinstance(values, pl.Series) else values\nif series.n_unique() != series.len():\n    series = series.unique()\ncategories = pl.Enum(series)","typeGuard":"def has_unique_categories(s: pl.Series) -> bool:\n    return s.n_unique() == s.len()","tryCatchPattern":"try:\n    dtype = pl.Enum(categories)\nexcept ValueError:\n    dtype = pl.Enum(categories.unique())","preventionTips":["Deduplicate inputs with .unique() or set() before constructing","Watch for Python enum aliases creating duplicate values","Assert uniqueness in unit tests for shared category definitions"],"tags":["polars","enum","duplicate","validation"],"backgroundTag":"invalid-argument-value","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}