I need the need to be able to encode/decode some application 'constants' into a single variable.
the best description would be analogous to the octal notation in chmod , and would work something like this :
class Permissions(MagicalExistingClassSomewhere):
EXECUTE = 1
WRITE = 2
READ = 4
a = Permissions(6)
print a
> [ Permissions.READ , Permissions.WRITE ]
a.add( Permissions.EXECUTE )
print a
> [ Permissions.READ , Permissions.WRITE , permissions.EXECUTE ]
print a.encode()
> 7
a.remove( Permissions.READ )
print a.encode()
> 3
has anyone seen a library that can abstract all the bitwise operations like this ? I've looked throughout PyPi and seen some libraries that focus on enum and bitwise, but nothing really does this sort of stuff.
There is some discussion and some source code for this kind of thing at https://codereview.stackexchange.com/questions/23187/bitwise-flag-code-for-python
It allows you to set flags like:
# define your flags
class sec(FlagType):
admin = 1
read = 2
write = 4
usage = 8
flags = +sec.read -sec.write +sec.usage
flags.read
>>> True
Lots of feedback saying its not Pythonic though :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With