(Python) Treat integer values as a set of flags

I implemented a Python class that treats integer values as a set of flags by treating each bit of the integer value as a flag.

It seems to be rarely useful.

Implementation

class IntFlags:
    """A class for treating integer values as a set of flags"""

    _alias = []

    def __init__(self, state: int = 0):
        if state < 0:
            raise ValueError
        object.__setattr__(self, "_state", state)

    def __getitem__(self, digit: int) -> bool:
        return (self._state & (1 << digit)) > 0

    def __setitem__(self, digit: int, value: bool):
        if type(value) is not bool:
            raise TypeError
        if self[digit] != value:
            object.__setattr__(self, "_state", self._state ^ (1 << digit))

    def __getattr__(self, key: str) -> bool:
        alias = type(self)._alias
        if key not in alias:
            raise AttributeError
        return self[alias.index(key)]

    def __setattr__(self, key: str, value: bool):
        alias = type(self)._alias
        if key not in alias:
            raise AttributeError
        self[alias.index(key)] = value

    def __int__(self) -> int:
        return self._state

    def __str__(self) -> str:
        return f"{self._state:0{len(type(self)._alias)}b}"
    
    def __repr__(self) -> str:
        return f'<{type(self).__name__} "{str(self)}">'

How to use

class UnixPermission(IntFlags):
    _alias = ["execute", "write", "read"]
    
    def __str__(self) -> str:
        return "".join(reversed([char if self[idx] else "-" for idx, char in enumerate("xwr")]))

If you inherit and create such a class, you can handle it as follows.

#Initialize
user_permission = UnixPermission(6)
user_permission  #=> <UnixPermission "rw-">
#Access individual flags
user_permission.read  #=> True
#Rewrite individual flags
user_permission.execute = True
user_permission  #=> <UnixPermission "rwx">
#Revert to an integer value
int(user_permission)  #=> 7

Recommended Posts

(Python) Treat integer values as a set of flags
python memo: Treat lists as a set type
Display a histogram of image brightness values in python
Python --Check type of values
Python: Create a dictionary from a list of keys and values
A set of script files that do wordcloud in Python3
[Python] Visualize overseas Japanese soccer players on a map as of 2021.1.1
Use pymol as a python library
A good description of Python decorators
Save the result of the life game as a gif with python
Format when passing a long string as an argument of python
[Python] A memorandum of beautiful soup4
A brief summary of Python collections
Ideone> Python version: 3.5 (as of August 29, 2017)
Use blender as a python module
Treat Python in-class variables as private variables
Launch a Python script as a service
If you want a singleton in python, think of the module as a singleton
Try to solve a set problem of high school math with Python
Install Python as a Framework with pyenv
Display a list of alphabets in Python 3
Make a relation diagram of Python module
Connect a lot of Python or and and
[Python] Sorting collection types as a reference
[python] Get a list of instance variables
[python] [meta] Is the type of python a type?
Python as a strongly, dynamically typed language
Set the process name of the Python program
[Python] Various combinations of strings and values
The story of blackjack A processing (python)
[Python] Get a list of folders only
A memorandum of python string deletion process
Python C / C ++ Extensions: Pass some of the data as np.array to Python (set stride)
Set up a simple HTTPS server in Python 3
[AtCoder] Solve A problem of ABC101 ~ 169 with Python
Combinatorial optimization --Typical problem-- Partition of a set problem
Example of taking Python> function> * args as arguments
[python] Create a list of various character types
Get the caller of a function in Python
A memorandum of calling Python from Common Lisp
Basic operation list of Python3 list, tuple, dictionary, set
[Python] Takes representative values โ€‹โ€‹of multiple images [Numpy]
Make a copy of the list in Python
A memorandum of extraction by python bs4 request
Set up a test SMTP server in Python.
Solve A ~ D of yuki coder 247 with python
Rewriting elements in a loop of lists (Python)
A note about the python version of python virtualenv
Make a joyplot-like plot of R in python
[Python] A rough understanding of the logging module
Output in the form of a python array
Set up a simple SMTP server in Python
Set up a Python development environment on Marvericks
Get a glimpse of machine learning in Python
[Python] A rough understanding of iterators, iterators, and generators
Proposal of Kuwahara filter as a photographic expression
A well-prepared record of data analysis in Python
A discussion of the strengths and weaknesses of Python
[Data science memorandum] Handling of missing values โ€‹โ€‹[python]
Set the output destination of the execution result to Vim started as a modeless window
Don't take an instance of a Python exception class directly as an argument to the exception class!