Opened 3 years ago

#6748 enhancement new

Document the use of Flags and FlagConstant with specific values

Reported by: Richard Wall Owned by:
Priority: normal Milestone:
Component: core Keywords: documentation
Cc: Branch:


The constants howto doesn't mention that you can supply a value to FlagConstant which is then used as the base for the following FlagConstant attributes without a specific value.

I guess this is useful for skipping particular bits.

In [23]: from twisted.python.constants import Flags, FlagConstant

In [24]: class BITS(Flags):
   ....:     one = FlagConstant()
   ....:     two = FlagConstant()
   ....:     eight = FlagConstant(8)
   ....:     sixteen = FlagConstant()

In [25]:
Out[25]: <BITS=one>

In [26]:
Out[26]: 1

In [27]: BITS.two.value
Out[27]: 2

In [28]: BITS.eight.value
Out[28]: 8

In [29]: BITS.sixteen.value
Out[29]: 16

You can also supply a number which isn't a power of two in which case all those bits will be shifted by subsequent FlagConstants. Not sure how that would be useful.

In [34]: class FLAGS2(Flags):
    three = FlagConstant(3)
    four = FlagConstant()
   ....:     eight = FlagConstant()

In [35]: FLAGS2.four.value
Out[35]: 6

In [36]: FLAGS2.eight.value
Out[36]: 12

In [37]: bin(FLAGS2.eight.value)
Out[37]: '0b1100'

In [38]: bin(FLAGS2.four.value)
Out[38]: '0b110'

I raised this ticket while trying to add missing epydoc to FlagConstant in #6570

Change History (0)

Note: See TracTickets for help on using tickets.