Skip to content

Fix Enum field by-name lookup to only return actual members#2902

Merged
sloria merged 4 commits intomarshmallow-code:devfrom
bysiber:fix/enum-deserialize-non-member
Mar 25, 2026
Merged

Fix Enum field by-name lookup to only return actual members#2902
sloria merged 4 commits intomarshmallow-code:devfrom
bysiber:fix/enum-deserialize-non-member

Conversation

@bysiber
Copy link
Copy Markdown
Contributor

@bysiber bysiber commented Feb 20, 2026

Summary

The Enum field's by-name deserialization uses getattr(self.enum, val) to look up members. However, getattr returns any attribute of the Enum class, not just actual enum members. This means inputs like "mro", "__class__", or "__members__" silently return non-Enum objects instead of raising a validation error.

Problem

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2

# Current behavior - these don't raise errors:
getattr(Color, "mro")         # <built-in method mro>
getattr(Color, "__members__")  # mappingproxy({...})
getattr(Color, "__class__")    # <class 'EnumType'>

When a user submits one of these attribute names as input, the Enum field returns the raw attribute/method object instead of an Enum member. Downstream code expecting an Enum member would break or behave unpredictably.

Fix

Replace getattr(self.enum, val) with self.enum[val]. The [] operator on Enum classes only looks up actual members (via EnumMeta.__getitem__), so non-member names correctly raise KeyError, which we catch and convert to a validation error.

# Before
getattr(Color, "mro")     # returns <built-in method mro>

# After  
Color["mro"]               # raises KeyError
Color["RED"]               # returns Color.RED ✓

Use dict-style access (self.enum[val]) instead of getattr(self.enum, val)
for by-name deserialization. getattr returns any attribute of the Enum
class, not just members. For example, passing "mro" or "__class__" would
return built-in methods/attributes instead of raising a validation error.

The enum item access operator [] only looks up actual enum members,
so non-member attribute names now correctly raise a validation error.
Copy link
Copy Markdown
Member

@sloria sloria left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Mind adding a test and adding yourself to AUTHORS.rst?

@sloria sloria enabled auto-merge (squash) March 25, 2026 22:29
@sloria sloria merged commit 024b5d0 into marshmallow-code:dev Mar 25, 2026
8 of 9 checks passed
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

Successfully merging this pull request may close these issues.

3 participants