Combine bitwise permission flags with enum.Flag and enum.IntFlag.
What You Will Learn
Flag provides named bitmask combinations with restricted numeric interoperability, while IntFlag also subclasses int. Powers-of-two values represent independent flags and are combined with the | operator.
Use IntFlag when interoperability with existing integer bitmasks is required.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from enum import Flag, auto
class Permission(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
allowed_permissions = Permission.READ | Permission.WRITE
print(Permission.READ in allowed_permissions)
print(Permission.EXECUTE in allowed_permissions)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: enum.
- The class Permission groups data and behavior; its methods run when called on an instance.
- The variable allowed_permissions holds the result of Permission.READ | Permission.WRITE. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
True
False
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Create read/write/admin flag combinations and test membership.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Giving unrelated flags overlapping bit values accidentally.
- Using ordinary integer arithmetic instead of bitwise operators to combine flags.
Key Takeaways
- Combine bitwise permission flags with enum.Flag and enum.IntFlag.
- Flag provides named bitmask combinations with restricted numeric interoperability, while IntFlag also subclasses int.
- Use IntFlag when interoperability with existing integer bitmasks is required.